I need to put a transparent boxplot on another image with grid. I create an image with a size based on data I pass. Once the boxplot is drawn, the initial size of the image has changed. Here my part of code with further explications:
png_width = 280
png_height = 120
px = 1 / plt.rcParams['figure.dpi'] # pixel in inches
fig_width = math.ceil((png_width / 60) * (max(data) - min(data)))
fig_cnt = 1
fig = plt.figure(fig_cnt, figsize=(fig_width * px, png_height * px), frameon=False, clear=True)
ax = fig.add_subplot(111)
bp = ax.boxplot(data, vert=False, widths=0.2, whis=[0, 100], )
for median in bp['medians']:
median.set(color='#000000')
plt.axis('off')
plt.savefig(filepath, bbox_inches='tight', pad_inches=0, transparent=True)
plt.close()
For a given set of data I have min=3 and max=60. fig_width=266px which is correct. Now I want to draw a boxplot where the distance from the first whisker to the second is also 266px. In my example the saved image has only 206px. I do not need any axis on the boxplot, only the boxplot itself. Why isn't the initial image size not maintained?
CodePudding user response:
There is a default margin around the subplots, so set the axes
to the whole fig
area by
fig.subplots_adjust(0, 0, 1, 1)
and your saved image is exactly 266 px wide.
The distance between the whiskers' ends will be smaller due to autoscaling. If you want the whiskers to use up the entire x-axis you can set the x limits accordingly:
ax.set_xlim(bp['whiskers'][0].get_xdata()[1], bp['whiskers'][1].get_xdata()[1])
(you may want to increase the limits a bit to see the full line width of the caps)