Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale Seaborn's y-axis with a bar plot

I'm using factorplot(kind="bar").

How do I scale the y-axis, for example with log-scale?

I tried tinkering with the plots' axes, but that always messed up the bar plot in one way or another, so please try your solution first to make sure it really works.

like image 309
user124114 Avatar asked Nov 19 '14 14:11

user124114


People also ask

How do you change the Y axis scale on a bar in Python?

To set the axis limit, we use setp() function with ylim() function. To display the graph, use show() function.


2 Answers

Considering your question mentions barplot I thought I would add in a solution for that type of plot also as it differs from the factorplot in @Jules solution.

import random import matplotlib.pyplot as plt import seaborn as sns sns.set(style="whitegrid")  xs = ["First", "First", "Second", "Second", "Third", "Third"] hue = ["Female", "Male"] * 3 ys = [1988, 301, 860, 77, 13, 1]  g = sns.barplot(x=xs, y=ys, hue=hue) g.set_yscale("log") _ = g.set(xlabel="Class", ylabel="Survived") 

enter image description here

And if you want to label the y-axis with non-logarithmic labels you can do the following.

import random import matplotlib.pyplot as plt import seaborn as sns sns.set(style="whitegrid")  xs = ["First", "First", "Second", "Second", "Third", "Third"] hue = ["Female", "Male"] * 3 ys = [1988, 301, 860, 77, 13, 1]  g = sns.barplot(x=xs, y=ys, hue=hue) g.set_yscale("log")  # the non-logarithmic labels you want ticks = [1, 10, 100, 1000] g.set_yticks(ticks) g.set_yticklabels(ticks)  _ = g.set(xlabel="Class", ylabel="Survived") 

enter image description here

like image 114
Michael Hall Avatar answered Sep 21 '22 02:09

Michael Hall


Note that seaborn.factorplot was renamed to seaborn.catplot

import seaborn as sns import matplotlib.pyplot as plt      titanic = sns.load_dataset("titanic")  g = sns.catplot(x="class", y="survived", hue="sex",                    data=titanic, kind="bar",                    height=5, palette="muted", legend=False, log=True) plt.show() 

enter image description here

You can use Matplotlib commands after calling factorplot. For example:

g = sns.factorplot(x="class", y="survived", hue="sex",                    data=titanic, kind="bar",                    height=5, palette="muted", legend=False) g.fig.get_axes()[0].set_yscale('log') plt.show() 

enter image description here

like image 43
Jules Avatar answered Sep 21 '22 02:09

Jules