How to adjust size of Seaborn distribution graph - python

I would like to adjust the size of this distribution plot in Seaborn. I tried a few ways from online tutorials and the docs but nothing seemed to actually work. I find this really confusing as it appears different plots such as plt, sns have different functions which don't seem to work interchangeably...
My code:
import seaborn as sns
g = sns.distplot(df['data'])
g.fig.set_figwidth(20)
g.fig.set_figheight(10)

g is an matplotlib.axes._subplots.AxesSubplot (try type(g) to see that). If you do a dir(g) you would see that it has no fig method/attribute. But it has a figure attribute. So change your code to reflect that and you would have what you need.
import seaborn as sns
g = sns.distplot(df['data'])
g.figure.set_figwidth(20)
g.figure.set_figheight(10)

Thanks #Sinan Kurmus's answer, just an alternative solution:
plt.figure(figsize=(30,10)) # Use this line
# plt.gcf().subplots_adjust(left = 0.3)
g = sns.distplot(df['data'])

Related

Statistical significance on matplotlib / seaborn graph?

I finished analyzing my data and want to show that they are statistically significant using the t-test_ind. However, I haven't found anything functional to show this other than what was referenced in (How does one insert statistical annotations (stars or p-values) into matplotlib / seaborn plots?):
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from statannot import add_stat_annotation
ax = sns.barplot(x=x, y=y, order=order)
add_stat_annotation(ax, data=df, x=x, y=y,
boxPairList=[(order[0], order[1]), (order[0], order[2])],
test='t-test_ind',
textFormat='star',
loc='outside')
Using this approach however, whenever I try to save the plot using plt.savefig() the added significancies using the add_stat_annotation are discared (matplotlib does not seem to recognize the added annotations). Using the loc='inside' option messes up my plot so it isn't really an option.
I am therefore asking if there is some simpler way to add the sigificancies directly in matplotlib / seaborn or if you can plt.savefig() with enough border / padding to include everything.
It was mainly a xlabel cut off problem. So in future applications I would use the add_stat_annotation from webermarcolivier/statannot. To save your files use one of the following possibilities:
import matplotlib.pyplot as plt
plt.tight_layout() # Option 1
plt.autoscale() # Option 2
plt.savefig('filename.png', bbox_inches = "tight") # Option 3
Hope this will help someone for future use.

Matplotlib: how do I know which colormap is being used?

I played around with colormaps, trying many of them, trying to make my own, both in matplotlib and seaborn.
However now I would like to know which colormap I am using. How can I do that? Is there a command like matplotlib.whichColormap ?
Usually there would be no need to find out the colormap you are using because you define that yourself. I.e. when calling
plt.imshow(..., cmap="viridis")
you already know that you are using "viridis".
If you still feel it would be useful to get that information from an existing ScalarMappable, you may use get_cmap() and it's name attribute:
import matplotlib.pyplot as plt
import numpy as np
a = np.random.rand(4,5)
fig, ax = plt.subplots()
im = ax.imshow(a, cmap="viridis")
cm = im.get_cmap()
print(cm.name) # prints viridis

In Python's Seaborn, is there any way to do the opposite of `despine`?

seaborn is a beautiful Python package that acts, for the most part, as an additional layer on top of matplotlib. However, it changes, for instance, things that would be matplotlib methods on a plot object to direct seaborn functions.
seaborn's despine() remove any spines (the outer edges of the plot) from a plot. But I cannot do the opposite.
I cannot seem to recreate the spine in the standard way that I would / could if I had used matplotlib entirely from the start. Is there a way to do that? How would I?
Below is an example. Could I, for instance, add a spine on the bottom and the left of the plot?
from sklearn import datasets
import pandas as pd
tmp = datasets.load_iris()
iris = pd.DataFrame(tmp.data, columns=tmp.feature_names)
iris['species'] = tmp.target_names[tmp.target]
iris.species = iris.species.astype('category')
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style('darkgrid')
sns.boxplot(x='species', y='sepal length (cm)', data=iris_new)
plt.show()
Thanks for all the great comments! I knew some of what you wrote, but not that both the 'axes.linewidth' and 'axes.edgecolor' needed to be set.
I'm writing an answer here, since it is a compilation of a few comments.
That is, the following code generates the plot below:
sns.set_style('darkgrid', {'axes.linewidth': 2, 'axes.edgecolor':'black'})
sns.boxplot(x='species', y='sepal length (cm)', data=iris_new)
plt.show()

How to show node labels when using matplotlib.pyplot?

I'm using Python to conduct social network analysis, very simple kind, and as a newbie (to both SNA and Python).
When drawing a graph using Terminal on my mac, I've tried every method I can but still can only draw nodes and edges, but no label of nodes in or beside them.
What scripts should I use to make the labels visible?
>>> import networkx as nx
>>> import networkx.generators.small as gs
>>> import matplotlib.pyplot as plt
>>> g = gs.krackhardt_kite_graph()
>>> nx.draw(g)
>>> plt.show()
EdChum gave a good answer. Another option which will by default not show the axes and produces a graph that takes up slightly more of the figure is to use nx.draw but give it the argument with_labels = True. (for nx.draw, you need to set with_labels to True, but for nx.draw_networkx it defaults to True).
import networkx as nx
import networkx.generators.small as gs
import matplotlib.pyplot as plt
g = gs.krackhardt_kite_graph()
nx.draw(g,with_labels=True)
plt.savefig('tmp.png')
Be aware that there is a bug such that sometimes plt.show() will not show the labels. From what I've been able to tell, it's not in networkx, but rather has something to do with the rendering. It saves fine, so I haven't worried about following up on it in detail. It shows up for me using ipython on a macbook. Not sure what other systems it's on. More detail at pylab/networkx; no node labels displayed after update
Try using draw_networkx:
import networkx as nx
import networkx.generators.small as gs
import matplotlib.pyplot as plt
g = gs.krackhardt_kite_graph()
nx.draw_networkx(g)
plt.show()
This results in:
with_labels is by default True so not necessary to specify

Setting plot background colour in Seaborn

I am using Seaborn to plot some data in Pandas.
I am making some very large plots (factorplots).
To see them, I am using some visualisation facilities at my university.
I am using a Compound screen made up of 4 by 4 monitors with small (but nonzero) bevel -- the gap between the screens.
This gap is black.
To minimise the disconnect between the screen i want the graph backgound to be black.
I have been digging around the documentation and playing around and I can't work it out..
Surely this is simple.
I can get grey background using set_style('darkgrid')
do i need to access the plot in matplotlib directly?
seaborn.set takes an rc argument that accepts a dictionary of valid matplotlib rcparams. So we need to set two things: the axes.facecolor, which is the color of the area where the data are drawn, and the figure.facecolor, which is the everything a part of the figure outside of the axes object.
(edited with advice from #mwaskom)
So if you do:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn
seaborn.set(rc={'axes.facecolor':'cornflowerblue', 'figure.facecolor':'cornflowerblue'})
fig, ax = plt.subplots()
You get:
And that'll work with your FacetGrid as well.
I am not familiar with seaborn but the following appears to let you change
the background by setting the axes background. It can set any of the ax.set_*
elements.
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
m=pd.DataFrame({'x':['1','1','2','2','13','13'],
'y':np.random.randn(6)})
facet = sns.factorplot('x','y',data=m)
facet.set(axis_bgcolor='k')
plt.show()
Another way is to set the theme:
seaborn.set_theme(style='white')
In new versions of seaborn you can also use
axes_style() and set_style() to quickly set the plot style to one of the predefined styles: darkgrid, whitegrid, dark, white, ticks
st = axes_style("whitegrid")
set_style("ticks", {"xtick.major.size": 8, "ytick.major.size": 8})
More info in seaborn docs

Categories

Resources