1

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')
3
  • I know that it sounds silly but have you tried saving it after displaying it - just a guess but the display may be doing extra layout that might be available after display? Commented Apr 28, 2014 at 12:45
  • I am quite sure that I have tried saving after, anyway I can double-check, no problem. Thanks. Commented Apr 28, 2014 at 12:52
  • Can you provide your code? Commented Apr 28, 2014 at 12:57

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Ahhhh very good!...Stupid matplotlib! :) Thanks very much. I will test it and post the result
You may need to vary the two values ((16, 4) in my case) to get a good result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.