Seaborn FacetGrid maximize size [duplicate] - python
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
Related
How to increase the figure size of a Seaborn Plot? [duplicate]
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
Change color of seaborn lineplot
I have a seaborn lineplot: plt.figure(figsize=(22,14)) sns.lineplot(x="Datum", y="Value", ci=None, hue='Type', data=df) plt.show() Which leads to the following output: How can i change the linecolors? For me the difference is hard to see.
You can change colors using palettes. Referring to https://seaborn.pydata.org/tutorial/color_palettes.html, try: import seaborn as sns; sns.set() import matplotlib.pyplot as plt fmri = sns.load_dataset("fmri") # Try playing with one set or another: #sns.set_palette("husl") sns.set_palette("PuBuGn_d") ax = sns.lineplot(x="timepoint", y="signal", hue="event", data=fmri) you'll get different line colors, like this or this
You can use colour inside lineplot() method, however this, far as I know, works only with Series. You can transform your data to Series with this this: data = pd.Series(another_data) Then plot Your data sns.lineplot(..., data=data, color='red') Another way is to use pallets palette = sns.color_palette("mako_r", 6) sns.lineplot(..., palette=palette, data=data) More you can find in Seaborn lineplot reference: https://seaborn.pydata.org/generated/seaborn.lineplot.html Or here: https://stackoverflow.com/a/58432483/12366487
At least in version 0.11.2 of seaborn, the lineplot function (http://seaborn.pydata.org/generated/seaborn.lineplot.html) has a parameter called palette that allows changing the color map used for the hue. To check the available color maps you can refer to https://matplotlib.org/stable/tutorials/colors/colormaps.html import seaborn as sns import matplotlib.pyplot as plt fmri = sns.load_dataset("fmri") #sns.lineplot(x="timepoint", y="signal", hue="event", data=fmri, palette="tab10") sns.lineplot(x="timepoint", y="signal", hue="event", data=fmri, palette="Accent")
Change y-axis scale - FacetGrid
I cannot work out how to change the scale of the y-axis. My code is: grid = sns.catplot(x='Nationality', y='count', row='Age', col='Gender', hue='Type', data=dfNorthumbria2, kind='bar', ci='No') I wanted to just go up in full numbers rather than in .5
Update I just now found this tutorial the probably easiest solution will be the following: grid.set(yticks=list(range(5))) From the help of grid.set Help on method set in module seaborn.axisgrid: set(**kwargs) method of seaborn.axisgrid.FacetGrid instance Set attributes on each subplot Axes. Since seaborn is build on top of matplotlib you can use yticks from plt import matplotlib.pyplot as plt plt.yticks(range(5)) However this changed only the yticks of the upper row in my mockup example. For this reason you probably want to change the y ticks based on the axis with ax.set_yticks(). To get the axis from your grid object you can implemented a list comprehension as follows: [ax[0].set_yticks(range(0,150,5) )for ax in grid.axes] A full replicable example would look like this (adapted from here) import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") exercise = sns.load_dataset("exercise") grid = sns.catplot(x="time", y="pulse", hue="kind", row="diet", data=exercise) # plt.yticks(range(0,150,5)) # Changed only one y-axis # Changed y-ticks to steps of 20 [ax[0].set_yticks(range(0,150,20) )for ax in grid.axes]
Will seaborn.barplot take the matplotlib.pyplot variable without any arguments passed?
I'm getting started with machine learning and I've been looking at a machine learning algorithm lately. I've seen seaborn.barplot take plt.figure to display the graph without any argument. How is that possible? fig = plt.figure(figsize = (7,7)) sns.barplot(x = 'quality',y = 'fixed acidity', data = wineData) fig is not passed as an argument to sns.barplot but it shows the graph according to figsize.
import numpy as np import matplotlib.pyplot as plt import seaborn as sns data = np.random.normal(0, 1, 3) # array([-1.18878589, 0.59627021, 1.59895721]) plt.figure(figsize=(16, 6)) sns.boxplot(x=data); In order to change the figure size of the seaborn package use matplotlib.pyplot.figure The seaborn function that draws a bar plot, use matplotlib.pyplot.figure with the figsize keyword
In the seaborn barplot code you find the following two lines: if ax is None: ax = plt.gca() This means, if no axes ax is provided by the user, the current axes from the current figure is taken. The current figure has been created by you with the given figure size. So seaborn plots its barplot to this figure.
How to plot a seaborn pairplot in an existing figure
I want seaborn to do a pairplot in an already defined figure. However it creates a new figure when sns.pairplot is called. For example, the following code creates two figures, the first blank and the second containg the pairplot. import seaborn as sns import matplotlib.pyplot as plt iris = sns.load_dataset('iris') fig,ax = plt.subplots(figsize=(9,9)) g = sns.pairplot(iris, hue='species') The reason I want to use the existing figure is so that I can change the figsize and other figure attributes easily. Any suggestions?
Use rcParams to specify figure attributes: plt.rcParams['figure.figsize']=(9,9) then plot without calling fig,ax = plt.subplots(figsize=(9,9)). You can not set existing fig instance according to FacetGrid class of seaborn. You can control figure size by number of columns and rows and with size and aspect arguments of pairplot. FacetGrid calculate figure size as figsize = (ncol * size * aspect, nrow * size).