I am ploting a graph in an application created with QtDesigner, the problem is that, when the grapth is showed, a big "grey edge" appears between the graph space and the mplwidget space. That makes the plot smaller, so how could I delete this big "grey border" that appears when I show my graph in the main Window??
I would like my graph to fill all the available space for the widget.
The short answer is: "Use fig.tight_layout()
."
Let me give a bit more explanation about what's going on, though.
You're seeing the interaction between the figure and the axes.
A Figure
contains one or more Axes
(plots/subplots/etc). Everything is drawn on the figure's Canvas
(basically, the backend-specific pixel buffer or vector page).
When you make an axes, it does not fill up all of the figure.
The default for a single axes is for the lower left corner of the axes to be a 12.5% of the width of the figure and 10% of the height and for the axes to take up 90% of the width and height of the figure. (The asymmetry is to leave room for the tick labels on the left.)
The position you set is the extent of the white box in the figure below. It doesn't include the tick labels, title, axes labels, etc (which is why the axes doesn't fill up the entire figure).
The default will look like this:
Side note: To keep the code short, I'm going to use the pyplot
interface to automatically generate a Figure
, Axes
, and Canvas
, while you're probably explicitly creating each one to work with your gui framework. The result is the same, though.
The percentage of the figure that each axes instance takes up is set at the time that it's created. You can either explicitly specify it:
fig = plt.figure()
ax = fig.add_axes([left, bottom, width, height])
Or use a grid of subplots, which can be easier to adjust through fig.subplots_adjust
:
fig, axes = plt.subplots(nrows=2, ncols=2)
# Expand the grid of subplots out (Notice that
fig.subplots_adjust(left=0.05, bottom=0.05, right=0.98, top=0.98)
What tight_layout
does is to calculate the extent of the tick labels, title, axis labels, etc and determine parameters for fig.subplots_adjust
such that everything will be just barely inside the figure. (Remember that subplots_adjust
and the axes position specification control the extent of the "white box" -- the actual axes itself -- and doesn't include the tick labels, etc.)
So, if we do just what we did before:
fig, ax = plt.subplots()
And then call:
fig.tight_layout()
We'll get something that has less of a "border", as the axes will take up a larger percentage of the figure:
If you want to control the color of the "border" use fig.set_facecolor(color)
(or fig.patch.set_facecolor
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With