draw artists over seaborn facetGrid - pandas

I would like to draw arrows over all panels of a facetGrid.
In this dummy example, I want to draw the same arrow on all panels:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pylab as plt
datDf=pd.DataFrame({'values':np.random.randint(0,100,100)})
datDf['group']=np.random.randint(0,5,100)
g = sns.FacetGrid(datDf, col="group",
col_wrap=3,
size=4.5,
sharex=True, sharey=True, despine=False)
g.map(plt.plot,'values')
for ax in g.axes:
arrow=plt.arrow(0,0,50,50,width=5,
length_includes_head=True,
head_width=5*2,
color='gray')
ax.add_artist(arrow)
I am receiving this error:
ValueError: Can not reset the axes. You are probably trying to re-use an artist in more than one Axes which is not supported
What is the correct way to draw artists on facetGrids?

You can use ax.arrow instead of plt.arrow to draw an arrow on the axes.
This should work:
for ax in g.axes:
ax.arrow(0,0,50,50,width=5,
length_includes_head=True,
head_width=5*2,
color='gray')

Related

numpy and matplotlib : Integration inside contour in a 2D plot

I have a function : z=f(x,y) and I draw a contour plot.
For example :
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
x=np.linspace(0,10,11)
y=np.linspace(0,10,11)
X,Y=np.meshgrid(x,y)
Z=(X+4)*(X-14)*(Y+6)*(Y-14)/1000
fig, ax =plt.subplots()
CS= ax.contour(x,x,Z,[7],colors='black')
ax.clabel(CS, inline=True, fontsize=10)
From the contour path data points (CS.collections[0].get_paths()[0]), how is it possible to integrate z inside this area ?
Thanks for answer.

matplotlib pyplot pcolor savefig colorbar transparency

I am trying to export a pcolor figure with a colorbar.
The cmap of the colorbar has a transparent color.
The exported figure has transparent colors in the axes but not in the colorbar. How can I fix this?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
x = np.random.random((10, 10))
colors = [(0,0,0,0), (0,0,0,1)]
cm = LinearSegmentedColormap.from_list('custom', colors, N=256, gamma=0)
plt.pcolor(x,cmap=cm)
plt.colorbar()
plt.savefig('figure.pdf',transparent=True)
I put the image against a grey background to check. As can be seen, the cmap in the axes is transparent while the one in the colorbar is not.
While the colorbar resides inside an axes, it has an additional background patch associated with it. This is white by default and will not be taken into account when transparent=True is used inside of savefig.
A solution is hence to remove the facecolor of this patch manually,
cb.patch.set_facecolor("none")
A complete example, which shows this without actually saving the figure
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
x = np.random.random((10, 10))
colors = [(1,1,1,0), (0,0,0,1)]
cm = LinearSegmentedColormap.from_list('custom', colors, N=256, gamma=0)
fig, ax = plt.subplots(facecolor="grey")
im = ax.pcolor(x,cmap=cm)
cb = fig.colorbar(im, drawedges=False)
ax.set_facecolor("none")
cb.patch.set_facecolor("none")
plt.show()

how to call axes and add it in a new figure in matplotlib

I want to combine the two figures in t1.py and t2.py. l import the two axis named ax1 int1.py and ax2 in t2.py in the new file t.py. now I set a figure in t.py, l want to add the imported two axes as subplots in the new figure, how can l do it?
I have tried one way to do it, but is not well enough:
this is t1.py file
import matplotlib.pyplot as plt
from t import ax01 as ax1
ax1.plot([2,4,5,6,9])
this is t2.py file
import matplotlib.pyplot as plt
from t import ax02 as ax1
ax1.plot([.2,.4,.5,.6,0.9])
this is t.py file
import matplotlib.pyplot as plt
fig1,(ax01,ax02)=plt.subplots(1,2);
execfile('t1.py')
execfile('t2.py')
plt.show()
however, this will call the execfile function.

Python3 Seaborn PairGrid legend outside subplots

I'm making a large PairGrid figure and I am unable to set the legend outside the plots (on the right). PairGrid doesn't seem to inherit the legend_out option of FaceGrid. Here is my attempt so far as you can see the legend overlaps the figure.
from random import choice
from numpy import random
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
def my_kdeplot(dfx, dfy, *args, **kwargs):
ax = sns.kdeplot(dfx, dfy, alpha=0.7,
cmap=sns.light_palette(kwargs['color'], as_cmap=True))
names = [choice('ABCDE') for _ in range(1000)]
df = pd.DataFrame(list(zip(names, *[random.random(1000) for _ in range(5)])),
columns=['names','A','B','C','D','E'])
g = sns.PairGrid(df, hue='names')
g.map_lower(my_kdeplot)
g.map_upper(plt.scatter, alpha=0.7)
g.map_diag(plt.hist)
g = g.add_legend(fontsize=14)
sns.plt.savefig('fig.png')
You can adjust the location of your legend using bbox_to_anchor=(horizontal, vertical):
g = g.add_legend(fontsize=14, bbox_to_anchor=(1.5,1))
You'll need to play with the numbers a little to find the right legend position.

Control gridline spacing in seaborn

I'd like to change the spacing of the horizontal grid lines on a seaborn chart, I've tried setting the style with no luck:
seaborn.set_style("whitegrid", {
"ytick.major.size": 0.1,
"ytick.minor.size": 0.05,
'grid.linestyle': '--'
})
bar(range(len(data)),data,alpha=0.5)
plot(avg_line)
The gridlines are set automatically desipite me trying to overide the tick size
Any suggestions? Thanks!
you can set the tick locations explicitly later, and it will draw the grid at those locations.
The neatest way to do this is to use a MultpleLocator from the matplotlib.ticker module.
For example:
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
sns.set_style("whitegrid", {'grid.linestyle': '--'})
fig,ax = plt.subplots()
ax.bar(np.arange(0,50,1),np.random.rand(50)*0.016-0.004,alpha=0.5)
ax.yaxis.set_major_locator(ticker.MultipleLocator(0.005))
plt.show()
The OP asked about modifying tick distances in Seaborn.
If you are working in Seaborn and you use a plotting feature that returns an Axes object, then you can work with that just like any other Axes object in matplotlib. For example:
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
from matplotlib.ticker import MultipleLocator
df = sm.datasets.get_rdataset("Guerry", "HistData").data
ax = sns.scatterplot('Literacy', 'Lottery', data=df)
ax.yaxis.set_major_locator(MultipleLocator(10))
ax.xaxis.set_major_locator(MultipleLocator(10))
plt.show()
Put if you are working with one of the Seaborn processes that involve FacetGrid objects, you will see precious little help on how to modify the tick marks without manually setting them. You have dig out the Axes object from the numpy array inside FacetGrid.axes .
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import MultipleLocator
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, )
g.axes[0][0].yaxis.set_major_locator(MultipleLocator(3))
Note the double subscript required. g is a FacetGrid object, which holds a two-dimensional numpy array of dtype=object, whose entries are matplotlib AxesSubplot objects.
If you are working with a FacetGrid that has multiple axes, then each one will have to be extracted and modified.