%pylab inline
import pandas as pd
import numpy as np
import matplotlib as mpl
import seaborn as sns
typessns = pd.DataFrame.from_csv('C:/data/testesns.csv', index_col=False, sep=';')
mpl.rc("figure", figsize=(45, 10))
sns.factorplot("MONTH", "VALUE", hue="REGION", data=typessns, kind="box", palette="OrRd");
I always get a small size figure, no matter what size I 've specified in figsize...
How to fix it?
Note added in 2019: In modern seaborn versions the size argument has been renamed to height.
To be a little more concrete:
%matplotlib inline
import seaborn as sns
exercise = sns.load_dataset("exercise")
# Defaults are size=5, aspect=1
sns.factorplot("kind", "pulse", "diet", exercise, kind="point", size=2, aspect=1)
sns.factorplot("kind", "pulse", "diet", exercise, kind="point", size=4, aspect=1)
sns.factorplot("kind", "pulse", "diet", exercise, kind="point", size=4, aspect=2)
You want to pass in the arguments 'size' or 'aspect' to the sns.factorplot() when constructing your plot.
Size will change the height, while maintaining the aspect ratio (so it will also also get wider if only size is changed.)
Aspect will change the width while keeping the height constant.
The above code should be able to be run locally in an ipython notebook.
Plot sizes are reduced in these examples to show the effects, and because the plots from the above code were fairly large when saved as png's. This also shows that size/aspect includes the legend in the margin.
size=2, aspect=1
size=4, aspect=1
size=4, aspect=2
Also, all other useful parameters/arguments and defaults for this plotting function can be viewed with once the 'sns' module is loaded:
help(sns.factorplot)
mpl.rc is stored in a global dictionary (see http://matplotlib.org/users/customizing.html).
So, if you only want to change the size of one figure (locally), it will do the trick:
plt.figure(figsize=(45,10))
sns.factorplot(...)
It worked for me using matplotlib-1.4.3 and seaborn-0.5.1
The size of the figure is controlled by the size and aspect arguments to factorplot. They correspond to the size of each facet ("size" really means "height" and then size * aspect gives the width), so if you are aiming for a particularl size for the whole figure you'll need to work backwards from there.
import seaborn as sns
sns.set(rc={'figure.figsize':(12.7,8.6)})
plt.figure(figsize=(45,10))
Output
Do not use %pylab inline, it is deprecated, use %matplotlib inline
The question is not specific to IPython.
use seaborn .set_style function, pass it your rc as second parameter or kwarg.: http://web.stanford.edu/~mwaskom/software/seaborn/generated/seaborn.set_style.html
If you just want to scale the figure use the below code:
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
sns.factorplot("MONTH", "VALUE", hue="REGION", data=typessns, kind="box", palette="OrRd"); // OR any plot code
Note as of July 2018:
seaborn.__version__ == 0.9.0
Two main changes which affect the above answers
The factorplot function has been renamed to catplot()
The size parameter has been renamed to height for multi plot grid functions and those that use them.
https://seaborn.pydata.org/whatsnew.html
Meaning the answer provided by #Fernando Hernandez should be adjusted as per below:
%matplotlib inline
import seaborn as sns
exercise = sns.load_dataset("exercise")
# Defaults are hieght=5, aspect=1
sns.catplot("kind", "pulse", "diet", exercise, kind="point", height=4, aspect=2)
Related
I want to create a output widget with several drop boxes and a plot with Seaborn as follows.
The intention is having different drop boxes to choose variables and according to user input output a different Seaborn plot.
Here the code. It works but not as desired.
dd = wd.Dropdown(
options=["YlGnBu","Blues","BuPu","Greens"],
value="Blues",
description='chosse cmap:',
disabled=False,
)
myout = wd.Output()
def draw_plot(change):
with myout:
myout.clear_output()
print('plotting out the following: sns.heatmap(df.corr(), annot=True, cmap = "YlGnBu")')
plt.figure(figsize=(8, 3))
sns.heatmap(df.corr(), annot=True, cmap = change.new)
plt.title("Correlation matrix");
dd.observe(draw_plot, names='value')
display(dd)
display(myout)
The above code DOES NOT CLEAR THE OUTPUT WIDGET every time a new variable of dropbox is selected, and Seaborn plots are added.
I saw these solutions:
Stop seaborn plotting multiple figures on top of one another
that are not satisfactory according to my opinion. I would like to display in the output widget a new figure every time, i.e. totally clear the content and then add stuff again; plot again.
I don't understand why clear_output() clears the text line but not the figure.
secondly, as some answers in the mentioned linked pointed out if working with Seaborn I don't want to resort to an underlying library, i.e. Matplotlib. I considere that a work around.
So how is the proper way to go?
thanks
The following code works for me.
I'm not sure if that was a typo, but you wrote clear_output() instead of myout.clear_output()
also, I believe you need to call plt.show() at the end of your callback.
import ipywidgets as wd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
a = np.random.random(size=(5,5))
dd = wd.Dropdown(
options=["YlGnBu","Blues","BuPu","Greens"],
value="Blues",
description='chosse cmap:',
disabled=False,
)
myout = wd.Output()
def draw_plot(change):
with myout:
print('plotting out the following: sns.heatmap(df.corr(), annot=True, cmap = "{}")'.format(change.new))
myout.clear_output()
sns.heatmap(a, annot=True, cmap = change.new)
plt.show()
dd.observe(draw_plot, names='value')
display(dd)
display(myout)
How do I change the size of my image so it's suitable for printing?
For example, I'd like to use to A4 paper, whose dimensions are 11.7 inches by 8.27 inches in landscape orientation.
You can also set figure size by passing dictionary to rc parameter with key 'figure.figsize' in seaborn set method:
import seaborn as sns
sns.set(rc={'figure.figsize':(11.7,8.27)})
Other alternative may be to use figure.figsize of rcParams to set figure size as below:
from matplotlib import rcParams
# figure size in inches
rcParams['figure.figsize'] = 11.7,8.27
More details can be found in matplotlib documentation
You need to create the matplotlib Figure and Axes objects ahead of time, specifying how big the figure is:
from matplotlib import pyplot
import seaborn
import mylib
a4_dims = (11.7, 8.27)
df = mylib.load_data()
fig, ax = pyplot.subplots(figsize=a4_dims)
seaborn.violinplot(ax=ax, data=df, **violin_options)
Note that if you are trying to pass to a "figure level" method in seaborn (for example lmplot, catplot / factorplot, jointplot) you can and should specify this within the arguments using height and aspect.
sns.catplot(data=df, x='xvar', y='yvar',
hue='hue_bar', height=8.27, aspect=11.7/8.27)
See https://github.com/mwaskom/seaborn/issues/488 and Plotting with seaborn using the matplotlib object-oriented interface for more details on the fact that figure level methods do not obey axes specifications.
first import matplotlib and use it to set the size of the figure
from matplotlib import pyplot as plt
import seaborn as sns
plt.figure(figsize=(15,8))
ax = sns.barplot(x="Word", y="Frequency", data=boxdata)
You can set the context to be poster or manually set fig_size.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10
# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)
sns.despine()
fig.savefig('example.png')
This can be done using:
plt.figure(figsize=(15,8))
sns.kdeplot(data,shade=True)
In addition to elz answer regarding "figure level" methods that return multi-plot grid objects it is possible to set the figure height and width explicitly (that is without using aspect ratio) using the following approach:
import seaborn as sns
g = sns.catplot(data=df, x='xvar', y='yvar', hue='hue_bar')
g.fig.set_figwidth(8.27)
g.fig.set_figheight(11.7)
This shall also work.
from matplotlib import pyplot as plt
import seaborn as sns
plt.figure(figsize=(15,16))
sns.countplot(data=yourdata, ...)
For my plot (a sns factorplot) the proposed answer didn't works fine.
Thus I use
plt.gcf().set_size_inches(11.7, 8.27)
Just after the plot with seaborn (so no need to pass an ax to seaborn or to change the rc settings).
See How to change the image size for seaborn.objects for a solution with the new seaborn.objects interface from seaborn v0.12, which is not the same as seaborn axes-level or figure-level plots.
Adjusting the size of the plot depends if the plot is a figure-level plot like seaborn.displot, or an axes-level plot like seaborn.histplot. This answer applies to any figure or axes level plots.
See the the seaborn API reference
seaborn is a high-level API for matplotlib, so seaborn works with matplotlib methods
Tested in python 3.8.12, matplotlib 3.4.3, seaborn 0.11.2
Imports and Data
import seaborn as sns
import matplotlib.pyplot as plt
# load data
df = sns.load_dataset('penguins')
sns.displot
The size of a figure-level plot can be adjusted with the height and/or aspect parameters
Additionally, the dpi of the figure can be set by accessing the fig object and using .set_dpi()
p = sns.displot(data=df, x='flipper_length_mm', stat='density', height=4, aspect=1.5)
p.fig.set_dpi(100)
Without p.fig.set_dpi(100)
With p.fig.set_dpi(100)
sns.histplot
The size of an axes-level plot can be adjusted with figsize and/or dpi
# create figure and axes
fig, ax = plt.subplots(figsize=(6, 5), dpi=100)
# plot to the existing fig, by using ax=ax
p = sns.histplot(data=df, x='flipper_length_mm', stat='density', ax=ax)
Without dpi=100
With dpi=100
# Sets the figure size temporarily but has to be set again the next plot
plt.figure(figsize=(18,18))
sns.barplot(x=housing.ocean_proximity, y=housing.median_house_value)
plt.show()
Some tried out ways:
import seaborn as sns
import matplotlib.pyplot as plt
ax, fig = plt.subplots(figsize=[15,7])
sns.boxplot(x="feature1", y="feature2",data=df) # where df would be your dataframe
or
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=[15,7])
sns.boxplot(x="feature1", y="feature2",data=df) # where df would be your dataframe
The top answers by Paul H and J. Li do not work for all types of seaborn figures. For the FacetGrid type (for instance sns.lmplot()), use the size and aspect parameter.
Size changes both the height and width, maintaining the aspect ratio.
Aspect only changes the width, keeping the height constant.
You can always get your desired size by playing with these two parameters.
Credit: https://stackoverflow.com/a/28765059/3901029
So I have this, probably, simple question. I created a histogram from data out of an excel file with seaborn. Forbetter visualization, I would like to have some space between the bars/bins. Is that possible?
My code looks as followed
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
%matplotlib inline
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('svg', 'pdf')
df = pd.read_excel('test.xlsx')
sns.set_style("white")
#sns.set_style("dark")
plt.figure(figsize=(12,10))
plt.xlabel('a', fontsize=18)
plt.ylabel('test2', fontsize=18)
plt.title ('tests ^2', fontsize=22)
ax = sns.distplot(st,bins=34, kde=False, hist_kws={'range':(0,1), 'edgecolor':'black', 'alpha':1.0}, axlabel='test1')
A second question though a bit off topic would be, how I get the exponent in the title of the chart to actually be uplifted?
Thanks!
The matplotlib hist function has an argument rwidth
rwidth : scalar or None, optional
The relative width of the bars as a fraction of the bin width.
You can use this inside the distplot via the hist_kws argument.
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
x = np.random.normal(0.5,0.2,1600)
ax = sns.distplot(x,bins=34, kde=False,
hist_kws={"rwidth":0.75,'edgecolor':'black', 'alpha':1.0})
plt.show()
for Seaborn >= 0.11, use shrink parameter. It scales the width of each bar relative to the binwidth by this parameter. The rest will be empty space.
Documentation: https://seaborn.pydata.org/generated/seaborn.histplot.html
edit:
OP was originally asking about sns.distplot(), however, it is deprecated in favor of sns.histplot or sns.displot() in the current version >=0.11. Since OP is generating a histogram, both histplot and displot in hist mode will take shrink
After posting my answer, I realized I answered the opposite of what was being asked. I found this question while trying to figure out how to remove the space between bars. I almost deleted my answer, but in case anyone else stumbles on this question and is trying to remove the space between bars in seaborn's histplot, I'll leave it for now.
Thanks to #miro for Seaborn's updated documentation, I found that element='step' worked for me. Depending on exactly what you want, element='poly' may be what you are after.
My implementation with 'step':
fig,axs = plt.subplots(4,2,figsize=(10,10))
i,j = 0,0
for col in cols:
sns.histplot(df[col],ax=axs[i,j],bins=100,element='step')
axs[i,j].set(title="",ylabel='Frequency',xlabel=labels[col])
i+=1
if i == 4:
i = 0
j+=1
My implementation with 'poly':
fig,axs = plt.subplots(4,2,figsize=(10,10))
i,j = 0,0
for col in cols:
sns.histplot(df[col],ax=axs[i,j],bins=100,element='poly')
axs[i,j].set(title="",ylabel='Frequency',xlabel=labels[col])
i+=1
if i == 4:
i = 0
j+=1
How do I change the size of my image so it's suitable for printing?
For example, I'd like to use to A4 paper, whose dimensions are 11.7 inches by 8.27 inches in landscape orientation.
You can also set figure size by passing dictionary to rc parameter with key 'figure.figsize' in seaborn set method:
import seaborn as sns
sns.set(rc={'figure.figsize':(11.7,8.27)})
Other alternative may be to use figure.figsize of rcParams to set figure size as below:
from matplotlib import rcParams
# figure size in inches
rcParams['figure.figsize'] = 11.7,8.27
More details can be found in matplotlib documentation
You need to create the matplotlib Figure and Axes objects ahead of time, specifying how big the figure is:
from matplotlib import pyplot
import seaborn
import mylib
a4_dims = (11.7, 8.27)
df = mylib.load_data()
fig, ax = pyplot.subplots(figsize=a4_dims)
seaborn.violinplot(ax=ax, data=df, **violin_options)
Note that if you are trying to pass to a "figure level" method in seaborn (for example lmplot, catplot / factorplot, jointplot) you can and should specify this within the arguments using height and aspect.
sns.catplot(data=df, x='xvar', y='yvar',
hue='hue_bar', height=8.27, aspect=11.7/8.27)
See https://github.com/mwaskom/seaborn/issues/488 and Plotting with seaborn using the matplotlib object-oriented interface for more details on the fact that figure level methods do not obey axes specifications.
first import matplotlib and use it to set the size of the figure
from matplotlib import pyplot as plt
import seaborn as sns
plt.figure(figsize=(15,8))
ax = sns.barplot(x="Word", y="Frequency", data=boxdata)
You can set the context to be poster or manually set fig_size.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10
# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)
sns.despine()
fig.savefig('example.png')
This can be done using:
plt.figure(figsize=(15,8))
sns.kdeplot(data,shade=True)
In addition to elz answer regarding "figure level" methods that return multi-plot grid objects it is possible to set the figure height and width explicitly (that is without using aspect ratio) using the following approach:
import seaborn as sns
g = sns.catplot(data=df, x='xvar', y='yvar', hue='hue_bar')
g.fig.set_figwidth(8.27)
g.fig.set_figheight(11.7)
This shall also work.
from matplotlib import pyplot as plt
import seaborn as sns
plt.figure(figsize=(15,16))
sns.countplot(data=yourdata, ...)
For my plot (a sns factorplot) the proposed answer didn't works fine.
Thus I use
plt.gcf().set_size_inches(11.7, 8.27)
Just after the plot with seaborn (so no need to pass an ax to seaborn or to change the rc settings).
See How to change the image size for seaborn.objects for a solution with the new seaborn.objects interface from seaborn v0.12, which is not the same as seaborn axes-level or figure-level plots.
Adjusting the size of the plot depends if the plot is a figure-level plot like seaborn.displot, or an axes-level plot like seaborn.histplot. This answer applies to any figure or axes level plots.
See the the seaborn API reference
seaborn is a high-level API for matplotlib, so seaborn works with matplotlib methods
Tested in python 3.8.12, matplotlib 3.4.3, seaborn 0.11.2
Imports and Data
import seaborn as sns
import matplotlib.pyplot as plt
# load data
df = sns.load_dataset('penguins')
sns.displot
The size of a figure-level plot can be adjusted with the height and/or aspect parameters
Additionally, the dpi of the figure can be set by accessing the fig object and using .set_dpi()
p = sns.displot(data=df, x='flipper_length_mm', stat='density', height=4, aspect=1.5)
p.fig.set_dpi(100)
Without p.fig.set_dpi(100)
With p.fig.set_dpi(100)
sns.histplot
The size of an axes-level plot can be adjusted with figsize and/or dpi
# create figure and axes
fig, ax = plt.subplots(figsize=(6, 5), dpi=100)
# plot to the existing fig, by using ax=ax
p = sns.histplot(data=df, x='flipper_length_mm', stat='density', ax=ax)
Without dpi=100
With dpi=100
# Sets the figure size temporarily but has to be set again the next plot
plt.figure(figsize=(18,18))
sns.barplot(x=housing.ocean_proximity, y=housing.median_house_value)
plt.show()
Some tried out ways:
import seaborn as sns
import matplotlib.pyplot as plt
ax, fig = plt.subplots(figsize=[15,7])
sns.boxplot(x="feature1", y="feature2",data=df) # where df would be your dataframe
or
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=[15,7])
sns.boxplot(x="feature1", y="feature2",data=df) # where df would be your dataframe
The top answers by Paul H and J. Li do not work for all types of seaborn figures. For the FacetGrid type (for instance sns.lmplot()), use the size and aspect parameter.
Size changes both the height and width, maintaining the aspect ratio.
Aspect only changes the width, keeping the height constant.
You can always get your desired size by playing with these two parameters.
Credit: https://stackoverflow.com/a/28765059/3901029
I'm using matplotlib to generate a (vertical) barchart. The problem is my labels are rather long. Is there any way to display them vertically, either in the bar or above it or below it?
Do you mean something like this:
>>> from matplotlib import *
>>> plot(xrange(10))
>>> yticks(xrange(10), rotation='vertical')
?
In general, to show any text in matplotlib with a vertical orientation, you can add the keyword rotation='vertical'.
For further options, you can look at help(matplotlib.pyplot.text)
The yticks function plots the ticks on the y axis; I am not sure whether you originally meant this or the ylabel function, but the procedure is alwasy the same, you have to add rotation='vertical'
Maybe you can also find useful the options 'verticalalignment' and 'horizontalalignment', which allows you to define how to align the text with respect to the ticks or the other elements.
In Jupyter Notebook you might use something like this
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
plt.xticks(rotation='vertical')
plt.plot(np.random.randn(100).cumsum())
or you can use:
plt.xticks(rotation=90)
Please check out this link:
https://python-graph-gallery.com/7-custom-barplot-layout/
import matplotlib.pyplot as plt
heights = [10, 20, 15]
bars = ['A_long', 'B_long', 'C_long']
y_pos = range(len(bars))
plt.bar(y_pos, heights)
# Rotation of the bars names
plt.xticks(y_pos, bars, rotation=90)
The result will be like this
Hopefully, it helps.
I would suggest looking at the matplotlib gallery. At least two of the examples seem to be relevant:
text_rotation.py for understanding how text layout works
barchart_demo2.py, an example of a bar chart with somewhat more complicated layout than the most basic example.