Question

I am creating a plot with matplotlib. Once I have the figure I am showing it inside a layout in my MainWindow, and the figure looks like this one:

enter image description here

Which looks good and everything is ok.

The problem is that, before showing it I am savin the figure with fig.savefig('EvolLine.png')

And the figure saved looks different. Then when I try to use this saved figure in a PDF file it does not look good.

Here it is the saved figure:

enter image description here

In addition, if I save the figure manually using the tool from the tool bar in the plot, then the saved figure looks good again.

I do not why if I save the figure "programatically" it looks bad, like compressed.

So how could I programatically save the figure and make it look like in the display??.

EDIT:

If that helps, this is the process that I am doing to save and plot:

fig = generateFigure(someData)
fig.savefig('EvolLine.png')
MyCanvas = FigureCanvas(fig)
navi_toolbar = NavigationToolbar(MyCanvas, self)
self.ui.verticalLayoutGraph4_3.addWidget(navi_toolbar)
self.ui.verticalLayoutGraph4_3.addWidget(MyCanvas)

#just to test
fig.savefig('EvolLine_AfterPlot.png')
Was it helpful?

Solution

Your problem is that when showing your figure in your program you are controlling the aspect ratio, meaning that the x-ticks do not overlap. However when saving the figure you are allowing matplotlib to automatically guess what it should be doing, and it's getting this wrong.

You can use fig.set_size_inches() to control the aspect ratio by setting an appropriate size, the code below demonstrates this as well as shows the different results.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,100,1000)
y = np.sin(x)

plt.plot(x,y)
plt.xticks(range(0,100,2))

fig = plt.gcf()
fig.set_size_inches(16,4)

plt.savefig('filename.png')

Original

Original

Fixed

Fixed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top