Control gridline spacing in seaborn - matplotlib

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.

Related

BoxPlot figure is not showing( just getting <AxesSubplot:>)

I am already having Tkinter(someone said to install a tkinter)
code used:
imports are:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
if u want to view the data-set then it is :
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/diabetes.csv")
code used to plot boxplot in jupyter notebook
fig, ax = plt.subplots(figsize = (20,20))
sns.boxplot(data = df,ax = ax)
)
I was supposed to add in my import's
%matplotlib inline

draw artists over seaborn facetGrid

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')

Circular dot on matplotlib barh graph

import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'y':['a','b','c','d','e','f','g','h','i']\
,'x':[10,9,9,8,7,6,10,6,7]})
df.sort_values(by='x',inplace=True,ascending = True)
plt.barh(bottom=list(range(1,10)), width=df.x, height = 0.15, align='center',color = 'blue')
plt.xlim([0,11])
plt.yticks(list(range(1,10)),skills.y)
plt.show()
This code gives me a horizontal bar graph.
I want to add a circular dot at the edge of each bars.
Can someone please help me with that.
Tableau graph
I did this in tableau, I want to replicate the same in python.
Also, please let me know if there a better way of coding the same.
I am using Anaconda Python 3.5, Matplotlib library, Windows 10, Idlex IDE
You could just add a scatterplot on top of your bars, using matplotlib scatter function.
Also, note that you could use the numpy.arange function to generate your x values, instead of your current list(range(1,10)).
See example below
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame({'y':['a','b','c','d','e','f','g','h','i'],
'x':[10,9,9,8,7,6,10,6,7]})
df.sort_values(by='x',inplace=True,ascending = True)
plt.barh(bottom=np.arange(len(df)), width=df.x, height = 0.15, align='center',color = 'blue')
plt.scatter(df.x.values, y=np.arange(df.shape[0]), color='b', s=40)
plt.xlim([0,11])
plt.yticks(np.arange(len(df)),df.y)
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.