pythonmatplotlibplotdata-visualizationsavefig

x axis label cropped on saved image


So I'm trying to do a bar plot on a data where x is the username (string ) and each x is long enough to overlap each other, so I have to rotate the x label. No problem there. However, when exporting the plot results, the x label on the exported image is cropped. I tried using plt.tight_layout() and worked, but it change the look of the plot. The code is similar to this


from matplotlib import pyplot as plt

x= ['abc', 'ronaldo', 'melon_killer_123456']
y= [1, 2, 3]

plt.bar(x, y)

plt.xticks(rotation = 90) 
plt.savefig('a.png')

plt.show()

Exported image:

wrong_image

I want it to look like this (Got this by using jupyter notebook and manually save output image):

correct_image

So how to do that?


Solution

  • You can play around with the rcParams size settings and the plt.subplots_adjust settings until you get your desired image.

    import matplotlib.pyplot as plt
    x= ['abc', 'ronaldo', 'melon_killer_123456']
    y= [1, 2, 3]
    
    plt.rcParams["figure.figsize"] = (5,10)
    plt.bar(x, y)
    plt.xticks(rotation = 90) 
    plt.subplots_adjust(top=0.925, 
                        bottom=0.20, 
                        left=0.07, 
                        right=0.90, 
                        hspace=0.01, 
                        wspace=0.01)
    plt.savefig('a.png')
    plt.show()