Matplotlib: how to edit a figure that has been closed - python-3.x

import matplotlib.pyplot as plt
a = plt.figure(1)
plt.plot([1,2,3,4])
a.show()
after closing the canvas I can show the figure stored in variable a at any time using a.show(), but how can I edit this figure?

As with most things matplotlib, you should keep track of your Figure and Axes objects directly. The you can do "anything"
So your example becomes:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3,4])
fig.show()
# <close the figure>
ax.set_xlabel('Post-mortem')

Related

How to set x ticks for seaborn (python) line plot

I made a line plot chart for years 1960-2014 using seaborn but the xticks aren't correct. I want only intervals to appear (like 1960, 1970, 1980, etc).How do i adjust the xticks? I tried rotating it but it didn't seem to work. Here is my code:
#plot figure using sns
g=sns.relplot(x="Year", y="Indicator_Value",
data=Emissions_C_df,
kind="line",
style="Indicator_Name",
hue="Indicator_Name",
)
plt.show()
You can use a MaxNLocator from matplotlib.ticker for the major ticks (decades) and manually set specific minor ticks with a FixedLocator.
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FixedLocator, MaxNLocator
a = np.arange(50)
d = {'Year': 1953+a, 'Indicator_Value': a}
df = pd.DataFrame(data=d)
g = sns.relplot(x="Year", y="Indicator_Value",
data=df,
kind="line")
ax = plt.gca()
ax.xaxis.set_major_locator(MaxNLocator(steps=[10]))
ax.xaxis.set_minor_locator(FixedLocator(range(1960,1970)))
plt.show()

How to set figure size in lmplot seaborn? [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

Python figure with the entire set of labels

I am trying to generate a figure to visualize the entire covariance matrix.
However, I am not able to include the entire list of labels. See the working example below:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm as cm
numberYears=len(range(2002,2018+1))
covMatrix=np.ones([numberYears,numberYears])
for count1,year1 in enumerate(range(2002,2018+1)) :
for count2,year2 in enumerate(range(2002,2018+1)) :
covMatrix[count1,count2]=1-(abs(count1-count2)/numberYears)
fig = plt.figure()
ax1 = fig.add_subplot(111)
cmap = cm.get_cmap('rainbow', 30)
cax = ax1.imshow(covMatrix, interpolation="nearest", cmap=cmap)
labels=[]
for year in range(2002,2018+1):
labels.append(str(year))
ax1.set_xticklabels(labels,fontsize=10,rotation=90)
ax1.set_yticklabels(labels,fontsize=10)
fig.colorbar(cax, ticks=[.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0])
fig.savefig('map.png')
Note that my labels are [2002,2003,...,2017,2018] and the entire list is not included as a label of the figure. How can I deal with this?
Considering #ImportanceOfBeingErnest comment, I was able to find the solution. I include the argument "extent" in the function "imshow" and I also "set.xticks":
from matplotlib import pyplot as plt
from matplotlib import cm as cm
numberYears=len(range(2002,2018+1))
covMatrix=np.ones([numberYears,numberYears])
for count1,year1 in enumerate(range(2002,2018+1)) :
for count2,year2 in enumerate(range(2002,2018+1)) :
covMatrix[count1,count2]=1-(abs(count1-count2)/numberYears)
fig = plt.figure()
ax1 = fig.add_subplot(111)
cmap = cm.get_cmap('rainbow', 30)
cax = ax1.imshow(covMatrix, interpolation="nearest", cmap=cmap,extent=[2002,2018,2002,2018])
labels=[]
for year in range(2002,2018+1):
labels.append(str(year))
ax1.set_xticks(listYears)
ax1.set_yticks(listYears)
ax1.set_xticklabels(labels,fontsize=10,rotation=90)
ax1.set_yticklabels(labels,fontsize=10)
fig.colorbar(cax, ticks=[.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0])
fig.savefig('mapTeste.png')

add a line to matplotlib subplots

I would like to do a subplot of two figures with matplotlib and add a horizontal line in both. This is probably basic, but I don't know how to specify that one of the lines should be drawn in the first figure, they both end up in the last one. e.g.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.rand(10))
fig, axes = plt.subplots(nrows=2,ncols=1)
f1= s1.plot(ax=axes[0])
l1=plt.axhline(0.5,color='black',ls='--')
l1.set_label('l1')
f2= s1.plot(ax=axes[1])
l2=plt.axhline(0.7,color='red',ls='--')
l2.set_label('l2')
plt.legend()
axhline does not have "ax" as an argument, as the pandas plot function does. So this would work:
l1=plt.axhline(0.5,color='black',ls='--',ax=axes[0])
I read the examples in matplotlib and I tried with this other option that does not work either (probably for good reasons)
axes[0].plt.axhline(0.5,color='black',ls='--')
How should I do to draw lines in subplots? Ideally with a legend Thanks!
with the help of #Nick Becker I answered my own "syntax" question.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.randn(10))
fig, axes = plt.subplots(nrows=2,ncols=1)
f1= s1.plot(ax=axes[0],label='s1')
l1=axes[0].axhline(0.5,color='black',ls='--')
l1.set_label('l1')
axes[0].legend(loc='best')
f2= s1.plot(ax=axes[1],label='s2')
l2=axes[1].axhline(0.5,color='black',ls='--')
l2.set_label('l2')
axes[1].legend(loc='best')

Plot shows automatically

I have a strange problem when plotting with matplotlib
Here is a sample code
from matplotlib.pyplot import *
for i in range(100):
plot(range(10))
xlabel("x")
This code will pop-up 100 times a figure. It seems that show() is called automatocally.
How can I make sure that after the plots no plot-windows are showed?
You can force it to use only one figure like:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(100):
ax.plot(range(10))
ax.set_xlabel("x")

Resources