36

我正在使用factorplot(kind="bar").

如何缩放 y 轴,例如使用对数刻度?

我尝试修改绘图轴,但这总是以某种方式弄乱条形图,因此请先尝试您的解决方案以确保它确实有效。

4

3 回答 3

44

考虑到您提到的问题barplot,我想我也会为这种类型的情节添加一个解决方案,因为它与factorplot@Jules 中的解决方案不同。

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

在此处输入图像描述

如果您想用非对数标签标记 y 轴,您可以执行以下操作。

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

在此处输入图像描述

于 2017-06-26T04:44:09.473 回答
22

请注意,seaborn.factorplot已重命名为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()

在此处输入图像描述

调用后可以使用 Matplotlib 命令factorplot。例如:

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

在此处输入图像描述

于 2014-11-24T15:04:34.393 回答
7

如果您在使用以前的解决方案设置对数刻度时遇到条形消失的问题,请尝试添加log=True到 seaborn 函数调用中。(我缺乏评论其他答案的声誉)。

使用sns.factorplot

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot(x="class", y="survived", hue="sex", kind='bar',
                   data=titanic, palette="muted", log=True)
g.ax.set_ylim(0.05, 1)

使用sns.barplot

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.barplot(x="class", y="survived", hue="sex",
                data=titanic, palette="muted", log=True)
g.set_ylim(0.05, 1)
于 2017-10-30T10:17:49.543 回答