python - Seaborn 子图保留不同的 x 标签

标签 python matplotlib plot seaborn

我试图保持 2 个子条形图的 x 标签的顺序。 问题是,当我运行脚本时,第二个子图标签会更新第一个子图标签,从而伪造值...

df1 = pd.DataFrame({"myindex":["Tuesday", "Thursday", "Monday", "Wednesday", "Friday"], "myvalues":[20000,18000,16000,12000, 10000]}) 
df2 = pd.DataFrame({"myindex":["Tuesday", "Thursday", "Friday", "Monday", "Wednesday"], "myvalues":[600,580,350,200,150]})
f, axes = plt.subplots(figsize=(12, 12), ncols=2, sharex=True)
sns.despine(left=True)

x, y1 = np.array(df1.myindex), (df1.myvalues)
g1 = sns.barplot(x, y1, ax=axes[0])
axes[0].set_xticklabels(labels=x, rotation=90)

x, y1 = np.array(df2.myvalues), (df2.myvalues)
g2 = sns.barplot(x, y1, ax=axes[1])
axes[1].set_xticklabels(labels=x, rotation=90)

这是由于我认为 set_xticklabels 函数不适合为两个子图设置 x 标签。 因此,1st 图的标签必须是:["Monday", "Tuesday", "Wednesday"],而 2nd 图的标签必须是:[“星期二”、“星期三”、“星期一”]。然而最后,1st 图的标签相当于 2nd 图的标签...

最佳答案

创建图形时,您使用 sharex = True 指定轴共享 x 轴。这意味着您最后一次调用的 axes.set_tickslabels() 将出现在两个图上。

解决方案是从图形初始化中删除sharex=True。带有一些虚假数据的完整示例:

import seaborn as sns
import matplotlib.pyplot as plt

f, axes = plt.subplots(figsize=(12, 12), ncols=2)
sns.despine(left=True)

x1 = ["Monday", "Tuesday", "Wednesday", "Thursday"]
y1 = [5,2,6,8]
g1 = sns.barplot(x1, y1, ax=axes[0])
axes[0].set_xticklabels(labels=x1, rotation=90)

x2 = [2,65,9,0]
y2 = [5,2,6,8]
g2 = sns.barplot(x2, y2, ax=axes[1])
axes[1].set_xticklabels(labels=x2, rotation=90)

plt.show()

这给出:

enter image description here

关于python - Seaborn 子图保留不同的 x 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48579733/

相关文章:

python - set_context 和 set_style 的 seaborn rc 参数

matlab - 你如何在 MATLAB 中使用 LaTeX 黑板字体?

python - 如何计算最近的半正定矩阵?

python - matplotlib 更改现有 skimage 图上的线宽

python - 在 python 中,如何将列表的多个值同时设置为零?

python - 删除Python中第一个实例后的字符串字符

python - Matplotlib 从 Pandas 数据框 groupby 中绘制图表

python - Matplotlib 副标题打印旧标题

python - 有没有办法用图例替换 matplotlib 子图(而不是将图例放在子图之外)?

r - 在ggvis中绘制堆积面积图的正确方法是什么?