How to render a matplotlib plot with hatch pattern to pdf with reportlab?

Viewed 26

I am unable to render correctly a matplotlib plot that contains hatch pattern to a pdf via reportlab.

Here is below a sample code that highlights the problem. The example is a simple but reportlab is needed in the project I am working on, so I cannot output straight to pdf from matplotlib.

from io import BytesIO

import matplotlib.pyplot as plt
import numpy as np
from reportlab.graphics import renderPDF
from reportlab.pdfgen import canvas
from svglib.svglib import svg2rlg

x = np.arange(100)
y = np.random.randint(50, 90, 100)

fig = plt.figure()
plt.plot(x, y, "o", color="b")
plt.axhspan(ymin=40, ymax=55, hatch="/", facecolor="none")
plt.show()

imgdata = BytesIO()
fig.savefig(imgdata, format="svg")
imgdata.seek(0)

drawing = svg2rlg(imgdata)
drawing.scale(0.5, 0.5)
c = canvas.Canvas("test.pdf")
renderPDF.draw(drawing, c, 10, 200)
c.drawString(100, 100, "No hatch pattern rendered")
c.showPage()
c.save()

The expected plot output is (as it is from matplotlib):

enter image description here

however, when exporting to pdf, I'm getting:

enter image description here

The culprit here seems to be svg2rlg that does not the following from the svg output of matplotlib:

    Can't handle color: url(#h06c0184332)

Is there a way to circumvent this problem while keeping the output from matplotlib as svg?

0 Answers
Related