Try to do a graph using python matplotlib: but keep getting the following waring message:
"UserWaring: tight_layout: falling back to Agg renderer warnings.warn("tight_layout: falling back to Agg renderer")
My code is below:
plt.legend(loc='upper left',prop = {'size':7},bbox_to_anchor=(1,1))
plt.tight_layout(pad=7)
plt.xlabel ('Build')
plt.ylabel ('Time/Sec')
plt.title ('Performance Test')
plt.grid()
plt.show()
How to fix that warning message?
Are you using MacOSX? It seems to be a known and open issue
https://github.com/matplotlib/matplotlib/issues/1852
I will suggest to reorganize the code such that you will use Figure instead of pyplot. You can get the Figure from plt.figure() method. Then, on the Figure instance call set_tight_layout(True).
Try this example code:
import matplotlib
matplotlib.use('pdf')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
fig.set_tight_layout(True)
fig.savefig('asd.pdf') # No warning now
As a side note, have a look at matplotlib documentation
tight_layout() can take keyword arguments of pad, w_pad and h_pad. These control the extra padding around the figure border and between subplots. The pads are specified in fraction of fontsize.
http://matplotlib.org/users/tight_layout_guide.html
This suggest that your code
plt.tight_layout(pad=7)
is wrong, as the value of pad should be between 0 and 1.
Related
Using the Spyder IDE, I have created a matplotlib plot and changed the face (background) color of both the figure object and the axes object to black. When I try to save the figure using plt.savefig(...) the axes, title, and axes label are not included.
I have tried implementing the standard advice of adding bbox_inches='tight' to the plt.savefig() function for when the axes are cut off:
plt.savefig("my_fig_name.png", bbox_inches='tight')
To no avail. Others suggested that I change the plotting method to "inline" from "automatic" within either Jupyter Notebook or Spyder. This had no effect. I also tried to make sure there was enough room in the figure for my axes using:
fig.add_axes([0.1,0.1,0.75,0.75])
This does not work either. Below is enough to reproduce my experience.
import matplotlib.pyplot as plt
xs, ys = [0,1], [0,1]
fig = plt.figure(figsize=(6, 6)) # Adding tight_layout=True has no effect
ax = fig.add_subplot(1, 1, 1)
# When the following block is commented out, the color of the
# plot is unchanged and the plt.savefig function works perfectly
fig.patch.set_facecolor("#121111")
ax.set_facecolor("#121111")
ax.spines['top'].set_color("#121111")
ax.spines['right'].set_color("#121111")
ax.spines['bottom'].set_color('white')
ax.spines['left'].set_color('white')
ax.xaxis.label.set_color('white')
ax.tick_params(axis='x', colors='white')
ax.yaxis.label.set_color('white')
ax.tick_params(axis='y', colors='white')
ax.set_title("My Graph's Title", color="white")
plt.plot(xs, ys)
plt.xlabel("x-label")
plt.ylabel("y-label")
plt.savefig("my_fig_name.png", bbox_inches="tight")
I am expecting to get an image like this:
What I Expect to Get
However, plt.savefig(...) gives me the following result:
What I Actually Get
Curiously, there seems to be white space around the plot which does not disappear even when I add the tight_layout=True parameter to the matplotlib figure constructor.
fig = plt.figure(figsize=(6, 6), tight_layout=True)
And, when I comment out the code which changes the face color of the plot, the figure is saved correctly with all the axes and labels displayed correctly.
In order to solve your problem, you just have to specify the facecolor keyword argument to your plt.savefig call, in this case :
plt.savefig("my_fig_name.png", bbox_inches="tight", facecolor="#121111")
which gives the intended .png output :
For more information, see plt.savefig documentation.
Updated MRE with subplots
I'm not sure of the usefulness of the original question and MRE. The margin padding seems to be properly adjusted for large x and y labels.
The issue is reproducible with subplots.
Using matplotlib 3.4.2
fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(8, 6))
axes = axes.flatten()
for ax in axes:
ax.set_ylabel(r'$\ln\left(\frac{x_a-x_b}{x_a-x_c}\right)$')
ax.set_xlabel(r'$\ln\left(\frac{x_a-x_d}{x_a-x_e}\right)$')
plt.show()
Original
I am plotting a dataset using matplotlib where I have an xlabel that is quite "tall" (it's a formula rendered in TeX that contains a fraction and is therefore has the height equivalent of a couple of lines of text).
In any case, the bottom of the formula is always cut off when I draw the figures. Changing figure size doesn't seem to help this, and I haven't been able to figure out how to shift the x-axis "up" to make room for the xlabel. Something like that would be a reasonable temporary solution, but what would be nice would be to have a way to make matplotlib recognize automatically that the label is cut off and resize accordingly.
Here's an example of what I mean:
import matplotlib.pyplot as plt
plt.figure()
plt.ylabel(r'$\ln\left(\frac{x_a-x_b}{x_a-x_c}\right)$')
plt.xlabel(r'$\ln\left(\frac{x_a-x_d}{x_a-x_e}\right)$', fontsize=50)
plt.title('Example with matplotlib 3.4.2\nMRE no longer an issue')
plt.show()
The entire ylabel is visible, however, the xlabel is cut off at the bottom.
In the case this is a machine-specific problem, I am running this on OSX 10.6.8 with matplotlib 1.0.0
Use:
import matplotlib.pyplot as plt
plt.gcf().subplots_adjust(bottom=0.15)
# alternate option without .gcf
plt.subplots_adjust(bottom=0.15)
to make room for the label, where plt.gcf() means get the current figure. plt.gca(), which gets the current Axes, can also be used.
Edit:
Since I gave the answer, matplotlib has added the plt.tight_layout() function.
See matplotlib Tutorials: Tight Layout Guide
So I suggest using it:
fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(8, 6))
axes = axes.flatten()
for ax in axes:
ax.set_ylabel(r'$\ln\left(\frac{x_a-x_b}{x_a-x_c}\right)$')
ax.set_xlabel(r'$\ln\left(\frac{x_a-x_d}{x_a-x_e}\right)$')
plt.tight_layout()
plt.show()
In case you want to store it to a file, you solve it using bbox_inches="tight" argument:
plt.savefig('myfile.png', bbox_inches="tight")
An easy option is to configure matplotlib to automatically adjust the plot size. It works perfectly for me and I'm not sure why it's not activated by default.
Method 1
Set this in your matplotlibrc file
figure.autolayout : True
See here for more information on customizing the matplotlibrc file: http://matplotlib.org/users/customizing.html
Method 2
Update the rcParams during runtime like this
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
The advantage of using this approach is that your code will produce the same graphs on differently-configured machines.
plt.autoscale() worked for me.
You can also set custom padding as defaults in your $HOME/.matplotlib/matplotlib_rc as follows. In the example below I have modified both the bottom and left out-of-the-box padding:
# The figure subplot parameters. All dimensions are a fraction of the
# figure width or height
figure.subplot.left : 0.1 #left side of the subplots of the figure
#figure.subplot.right : 0.9
figure.subplot.bottom : 0.15
...
There is also a way to do this using the OOP interface, applying tight_layout directly to a figure:
fig, ax = plt.subplots()
fig.set_tight_layout(True)
https://matplotlib.org/stable/api/figure_api.html
for some reason sharex was set to True so I turned it back to False and it worked fine.
df.plot(........,sharex=False)
You need to use sizzors to modify the axis-range:
import sizzors as sizzors_module
sizzors_module.reshape_the_axis(plt).save("literlymylief.tiff")
I am trying to plot data to a figure and respective axis in matplotlib and as new work comes up, recall the figure with the additional plot on the axis:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
x=np.arange(0,20)
y=2*x
fig,ax=plt.subplots()
ax.scatter(x,x)
ax.scatter(x,y)
fig
Which works fine with matplotlib, if I however use seaborn's regplot:
fig2,ax2=plt.subplots()
sns.regplot(x,x,ax=ax2,fit_reg=False)
sns.regplot(x,y,ax=ax2,fit_reg=False)
fig2
fig2 generates the figure that I want but the regplot command generates an empty figure. Is there a way to suppress the regplot's empty output or have it display the updated ax2 without recalling fig2?
It seems you are using the jupyter notebook with the inline backend. In some circumstances regplot triggers the creation of a new figure even if the artists are being added to the previous one and this messes up the output. I don't know why this happens but I found a workaround that might help you, using plt.ioff to temporarily disable automatic display of figures.
plt.ioff()
fig, ax = plt.subplots()
sns.regplot(x, x, ax=ax)
fig
sns.regplot(x, 2 * x, ax=ax)
fig
You have to call plt.ioff before creating the figure for this to work. After that you have to explicitly display the figure. Then you can call plt.ion to restore the default behaviour.
regplot does not generate an empty figure. According to the documentation:
Understanding the difference between regplot() and lmplot() can be a
bit tricky. In fact, they are closely related, as lmplot() uses
regplot() internally and takes most of its parameters. However,
regplot() is an axes-level function, so it draws directly onto an axes
(either the currently active axes or the one provided by the ax
parameter), while lmplot() is a figure-level function and creates its
own figure, which is managed through a FacetGrid.
When I do the following:
fig2,ax2 = plt.subplots()
same_fig2 = sns.regplot(x,x,ax=ax2,fit_reg=False)
same_fig2.figure is fig2
>>> True
I keep trying to follow the examples I see for PdfPages but keep getting the value error: No such figure: None.
plot1 = Chart Generating Function(argument1, argument2,...)
from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages('sample.pdf')
pp.savefig(plot1)
plt.close()
I've tried different variations of this (i.e. pdf.savefig()) but nothing seems to work.
What solved the problem for me was removing the plt.show() command at the end of my chart generating function.
I should have added more details, but somewhere in my code I had used "fig, ax = ..." when defining the figure. The "fig" part needed to be the argument in pdf.savefig(fig) in order for it to work.
I'm trying to plot two sets of data in a bar graph with matplotlib, so I'm using two axes with the twinx() method. However, the second y-axis label gets cut off. I've tried a few different methods with no success (tight_layout(), setting the major_pads in rcParams, etc...). I feel like the solution is simple, but I haven't come across it yet.
Here's a MWE:
#!/usr/bin/env python
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.rcParams.update({'font.size': 21})
ax = plt.gca()
plt.ylabel('Data1') #Left side
ax2 = ax.twinx()
for i in range(10):
if(i%2==0):
ax.bar(i,np.random.randint(10))
else:
ax2.bar(i,np.random.randint(1000),color='k')
plt.ylabel('Data2') #Right
side
plt.savefig("test.png")
I just figured it out: the trick is to use bbox_inches='tight' in savefig.
E.G. plt.savefig("test.png",bbox_inches='tight')
I encountered the same issue which plt.tight_layout() did not automatically solve.
Instead, I used the labelpad argument in ylabel/set_ylabel as such:
ax.set_ylabel('label here', rotation=270, color='k', labelpad=15)
I guess this was not implemented when you asked this question, but as it's the top result on google, hopefully it can help users of the current matplotlib version.