Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exporting pyplot historgram to illustrator has infinite bars

I am exporting a matplotlib histogram as a vector format to process in illustrator. This is how I do it

plt.savefig('figure.svg',format='svg',transparent=True)

However, when I try to copy the graph in illustrator I get

can't paste the objects. The requested transformation would make some objects fall completely off the drawing area. enter image description here

Turns out when I click on the object, the histogram bars have infinite length in illustrator.

I attached the figure to reproduce the error: https://cmapreg.s3.us-east-2.amazonaws.com/figure.svg and a screenshot.

like image 791
Marouen Avatar asked Aug 30 '25 17:08

Marouen


1 Answers

The problem

The issue seems to be caused not primarily by the log scale but by changing the ylim of the plot. This leaves the length of the original boxes in your plot the same and only changes the "window" visible in the figure. Exporting to illustrator as pdf gives you the original boxes, which, in the special case of a log scale, extend to minus infinity. Even without log scale the boxes would extend beyond the white figure canvas.

For example: This will produce the error described above when imported as pdf into illustrator:

plt.bar(np.arange(5), np.arange(5)+10, width=0.5, color='k')
plt.ylim(8, 16)
plt.show()

enter image description here

Solution 1

A possible solution is using the bottom parameter in either hist or bar, as mentioned by Jody's comment. Problem there is that this will shift your boxes upwards as well. You can counteract this by either subtracting the value in bottom from your barplot values or by changing the y-tick accordingly.

This will not produce the error, since we crop the bars below the lower ylim:

bottom=8
x = np.arange(5)
y = np.arange(5)+10
plt.bar(x, y - bottom, width=0.5, color='k', bottom=bottom)
plt.ylim(8, 16)
plt.show()

enter image description here

It looks exactly the same as the original plot, but without the import issue.

Solution 2

In case of the original question where we want to use the hist function to plot the boxes, we need to go for the second (and less elegant) option: since we can not adjust the heights of the boxes directly, we change the y-axis labels.

plt.hist(np.random.uniform(0,5,100), width=0.5, color='k', bottom=bottom)
plt.ylim(bottom, 16 + bottom)
pl.yticks(np.arange(bottom, 16 + bottom), np.arange(0, 16))
plt.show()

(I know this issue is old, but I could not find any solution posted elsewhere online.)

like image 135
McMillenandhiswife Avatar answered Sep 02 '25 19:09

McMillenandhiswife