I need some help to make my cph plot bigger, but unfortunately, it seems like figsize can't be applied on this plot! Can somebody help me please?
I'm using Jupyter Notebook on pandas!
cph.plot()
Here the problem is that the plot function actually plots my features, but they are too much so their names overlap and I can see nothing! I need the plot to be bigger!
Seems like cph.plot() calls matplotlib.pyplot.plot in the back-end. By default, Matplotlib uses the last created figure, so creating a figure with your specified width and height should do the trick:
import matplotlib.pyplot as plt
# 8, 12 => width and height in inches
plt.figure(figsize=(8, 12))
cph.plot(/*your params here*/)
See if this works.
you can try the following command:
import seaborn as sns
sns.set(rc={'figure.figsize':(18,10)})
cph.plot()
Related
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 learn python mainly for plotting. Here is my sample code:
import numpy as np
import matplotlib.pyplot as plt
a=[[1,2,3,4],[2,3,4,5],[3,4,5,6]]
x=np.arange(len(a[0]))
width=0.2
fig, ax = plt.subplots(figsize=(8,6))
patterns=['/','\\','*']
for bar in a:
ax.bar(x,bar,width,edgecolor='black',color='lightgray', hatch=patterns.pop(0))
x=x+width
plt.show()
Now the problem is that, I need black edge colour for all bars as well as given hatch patter. However, the formatting is applied to first set of bars only. Here is my output. (I am using python3).
What's missing here or what's wrong? I have looked around but did not find any fix.
Update:
I have tried different options :python2, python3 and pdf/png. Here are results
python2 png --fine
python3 png -- shown above
python2 pdf -- see
python3 pdf -- see
I have also tried 'backend' as matplotlib.use('Agg'). I have update my matplotlib version (2.1.0).
There is a current issue in matplotlib 2.1 that only the first bar's edgecolor is applied. The same for the hatch, see this issue. Also see this question.
It may be that you are using matplotlib 2.1 for python3 but not for python2, hence in python2 it works for you. If I run your code in python 2 with matplotlib 2.1 I get the same undesired behaviour.
The issue will be fixed, once matplotlib 2.1.1 is released.
In the meantime, a workaround is to set the edgecolor and hatch on the individual bars:
import numpy as np
import matplotlib.pyplot as plt
a=[[1,2,3,4],[2,3,4,5],[3,4,5,6]]
x=np.arange(len(a[0]))
width=0.2
fig, ax = plt.subplots(figsize=(8,6))
patterns=['/','\\','*']
for y in a:
bars = ax.bar(x,y,width,color='lightgray')
hatch= patterns.pop(0)
for bar in bars:
bar.set_edgecolor("black")
bar.set_hatch(hatch)
x=x+width
plt.show()
It looks something's wrong with edgecolor tuple's alpha value. Set it to 1 will solve the problem.
I'm brand new to Python, I just switched from Matlab. The distro is Anaconda 2.1.0 and I'm using the Spyder IDE that came with it.
I'm trying to make a scatter plot with equal ratios on the x and y axes, so that this code prints a square figure with the vertices of a regular hexagon plotted inside.
import numpy
import cmath
import matplotlib
coeff = [1,0,0,0,0,0,-1]
x = numpy.roots(coeff)
zeroplot = plot(real(x),imag(x), 'ro')
plt.gca(aspect='equal')
plt.show()
But plt.gca(aspect='equal') returns a blank figure with axes [0,1,0,1], and plt.show() returns nothing.
I think the main problem is that plt.gca(aspect='equal') doesn't just grab the current axis and set its aspect ratio. From the documentation, (help(plt.gca)) it appears to create a new axis if the current one doesn't have the correct aspect ratio, so the immediate fix for this should be to replace plt.gca(aspect='equal') with:
ax = plt.gca()
ax.set_aspect('equal')
I should also mention that I had a little bit of trouble getting your code running because you're using pylab to automatically load numpy and matplotlib functions: I had to change my version to:
import numpy
import cmath
from matplotlib import pyplot as plt
coeff = [1,0,0,0,0,0,-1]
x = numpy.roots(coeff)
zeroplot = plt.plot(numpy.real(x), numpy.imag(x), 'ro')
ax = plt.gca()
ax.set_aspect('equal')
plt.show()
People who are already comfortable with Python don't generally use Pylab, from my experience. In future you might find it hard to get help on things if people don't realise that you're using Pylab or aren't familiar with how it works. I'd recommend disabling it and trying to get used to accessing the functions you need through their respective modules (e.g. using numpy.real instead of just real)
I am using Seaborn to plot some data in Pandas.
I am making some very large plots (factorplots).
To see them, I am using some visualisation facilities at my university.
I am using a Compound screen made up of 4 by 4 monitors with small (but nonzero) bevel -- the gap between the screens.
This gap is black.
To minimise the disconnect between the screen i want the graph backgound to be black.
I have been digging around the documentation and playing around and I can't work it out..
Surely this is simple.
I can get grey background using set_style('darkgrid')
do i need to access the plot in matplotlib directly?
seaborn.set takes an rc argument that accepts a dictionary of valid matplotlib rcparams. So we need to set two things: the axes.facecolor, which is the color of the area where the data are drawn, and the figure.facecolor, which is the everything a part of the figure outside of the axes object.
(edited with advice from #mwaskom)
So if you do:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn
seaborn.set(rc={'axes.facecolor':'cornflowerblue', 'figure.facecolor':'cornflowerblue'})
fig, ax = plt.subplots()
You get:
And that'll work with your FacetGrid as well.
I am not familiar with seaborn but the following appears to let you change
the background by setting the axes background. It can set any of the ax.set_*
elements.
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
m=pd.DataFrame({'x':['1','1','2','2','13','13'],
'y':np.random.randn(6)})
facet = sns.factorplot('x','y',data=m)
facet.set(axis_bgcolor='k')
plt.show()
Another way is to set the theme:
seaborn.set_theme(style='white')
In new versions of seaborn you can also use
axes_style() and set_style() to quickly set the plot style to one of the predefined styles: darkgrid, whitegrid, dark, white, ticks
st = axes_style("whitegrid")
set_style("ticks", {"xtick.major.size": 8, "ytick.major.size": 8})
More info in seaborn docs
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.