I have some really simple figures that I'm trying to generate for an experiment. They're just supposed to be bars with 3 colors, each color representing a different probability for an event.
I approached this by creating a horizontal stacked barplot in matplotlib, then I tried removing the gridlines and margins and everything extra just so that I could see only the bars. The following
df = pd.DataFrame({"Risk":[95], "No Effect" : [3], "Gain":[2]})
df.plot(kind='barh', legend = False, stacked=True, color=['#FFFF00', '#808080', '#4169e1'])
plt.axis('off')
plt.margins(x=0)
plt.margins(y=0)
plt.grid(b=None)
plt.savefig('static/images/debug3red.png', bbox_inches='tight', pad_inches=-1)
plt.show()
This code snippet is basically what I compiled from reviewing a bunch of posts about people trying to accomplish the same task.
It's almost up to par.
Here's the image I get from plt.show(). There are still margins present, but this technically shouldn't be a problem because my savefig() call ideally should have the correct parameters to remove those margins.
Now here's the image that's saved from the savefig()
call.
The image is slightly zoomed in on, and cropped partially. You can't tell that the image has been zoomed in slightly from this image, there are other instances that I've seen that better showcase that property. But you can clearly see that the image is being cropped. There are no margins at least, but...
I'm close, but what's going wrong here and how can I actually accomplish my goal?
Edit: Also for those who might be wondering (because I've heard that "pad_inches=-1" isn't elegant)...
pad_inches = 0 produces the following (for a different set of probabilities)
Edit: Based off of this answer, Removing white space around a saved image in matplotlib
The following code removes the vertical margins, but doesn't remove the horizontal margins.
plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.savefig('static/images/debug5.png', bbox_inches='tight', pad_inches=0.0)