简体   繁体   中英

Missing images inserted by `matplotlib.imshow` in PDF when using `savefig`

I am trying to insert images to annotate a graph like this:

from matplotlib import offsetbox
from matplotlib import pyplot as plt
from matplotlib import rcParams

rcParams["figure.dpi"] = 200
rcParams["figure.figsize"] = 4,3
alphaEndo = pd.read_csv('../data/UNIT_VOL_FRACTION.ENDO_DODECAHEDRON.csv', comment="#")

fig, ax = plt.subplots()
ax.grid(False)

ax.set_ylabel("$\\alpha_c(s)$")
ax.set_xlabel("$s$")

colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

def plot_polyhedron(N, xScale, yScale, ax):
    img = plt.imread("../data/UNIT_VOL_ENDO_DODECAHEDRON_IMAGES/UNIT_VOL_ENDO_DODECAHEDRON.%04d.png" % N) 
    img = offsetbox.OffsetImage(img, zoom=0.07)
    img.image.axes = ax
    ab = offsetbox.AnnotationBbox(img, xy=(alphaEndo['S'].loc[N], alphaEndo['ALPHA_STAR'].loc[N]),
                                  xybox=(xScale*alphaEndo['S'].loc[N], yScale*alphaEndo['ALPHA_STAR'].loc[N]),
                                  frameon=False, arrowprops=dict(arrowstyle="Simple",facecolor=colors[0]),pad=False)
    ax.add_artist(ab)      

plot_polyhedron(5, 2, 0.6, ax)
plot_polyhedron(50,0.65, 0.35, ax)
plot_polyhedron(95, 0.7, 3, ax)
ax.plot(alphaEndo['S'], alphaEndo['ALPHA_STAR'], lw=2)


figBaseName = "ENDO_DODECAHEDRON_ALPHA_S"
fig.savefig(figBaseName + ".png")
fig.savefig(figBaseName + ".pdf")

if "GEOP" in os.environ:
    pathName = os.path.join(os.environ["GEOP"], "figures", figBaseName)
    fig.savefig(pathName + ".png")
    fig.savefig(pathName + ".pdf")

For the PNG file, I get this:

在此处输入图片说明

but in the PDF, the small images of the polyhedron are missing:

在此处输入图片说明

I found this question about missing images, but the answer doesn't really help in my case, because I am not explicitly calling "plt.show()" before "plt.savefig()", I'm using axes. The code is from a Jupyter notebook cell.

Please, try this modification:

def plot_polyhedron(N, xScale, yScale, ax):
    img = plt.imread("../data/UNIT_VOL_ENDO_DODECAHEDRON_IMAGES/UNIT_VOL_ENDO_DODECAHEDRON.%04d.png" % N) 
    imagebox = offsetbox.OffsetImage(img, zoom=0.07)
    imagebox.image.axes = ax
    ab = offsetbox.AnnotationBbox(imagebox, xy=(alphaEndo['S'].loc[N], alphaEndo['ALPHA_STAR'].loc[N]),
                                  xybox=(xScale*alphaEndo['S'].loc[N], yScale*alphaEndo['ALPHA_STAR'].loc[N]),
                                  frameon=False, arrowprops=dict(arrowstyle="Simple",facecolor=colors[0]),pad=False)
    ax.add_artist(ab)   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM