【问题标题】:Add percentage axis to Seaborn catplot with correct axis tick labels使用正确的轴刻度标签将百分比轴添加到 Seaborn catplot
【发布时间】:2021-01-22 17:52:46
【问题描述】:

我正在绘制一个分类变量的计数,并想添加第二个 y 轴来显示样本总数的百分比。

import matplotlib.pyplot as plt
import seaborn as sns

titanic = sns.load_dataset("titanic")

g = sns.catplot(x="alive", col="embark_town", col_wrap=4,
                data=titanic[titanic.deck.notnull()],
                kind="count", height=4, aspect=.8)

for i, ax in enumerate(g.axes.flat):
    
    # Create second y-axis for the percentages on the right
    ax1 = ax.twinx()
    
    ### Attempt to fix percentages by plotting the bars over
    #g = sns.catplot(x="alive", col="embark_town", col_wrap=4,
    #            data=titanic[titanic.deck.notnull()],
    #            kind="count", height=4, aspect=.8,
    #            ax = ax1)
    
    # Label by the percentages
    ax1.set_ylim(ax.get_ylim())
    ax1.set_yticklabels(np.round(ax.get_yticks()/titanic[titanic.deck.notnull()].shape[0],1))
    ax1.set_ylabel('Percentage')

    # Rotate x-labels
    labels = ax.get_xticklabels() # get x labels
    ax.set_xticklabels(labels, rotation=90)
  
# Ensure good spacing  
g.fig.tight_layout()

好的,现在我的问题是百分比在右侧 y 轴上重复,如下图所示

我试图通过在新轴上绘制计数来纠正此问题,但这会添加另一行子图(请参阅 for 循环中注释掉的代码)。如何获得正确的 y 轴标签以不包含重复值并实际反映总数的百分比?

【问题讨论】:

  • 您的标签显示为“重复”,因为您将比率四舍五入到小数点后一位(只需将1 更改为3 即可查看差异)。也许将它们乘以100,例如像这样:percent = (ax.get_yticks() / titanic[titanic.deck.notnull()].shape[0] * 100).astype('int')ax1.set_yticklabels(percent) `
  • 哈哈哈好收获!

标签: python-3.x matplotlib seaborn


【解决方案1】:
import matplotlib.pyplot as plt
import seaborn as sns

titanic = sns.load_dataset("titanic")

g = sns.catplot(x="alive", col="embark_town", col_wrap=4,
                data=titanic[titanic.deck.notnull()],
                kind="count", height=4, aspect=.8)

# calculate numbre of samples:
total_samples = len(titanic[titanic.deck.notnull()])


for i, ax in enumerate(g.axes.flat):
    
#     bounds of the left y-axis:
    ymin, ymax = ax.get_ylim()    
    
#     # Create second y-axis for the percentages on the right    
    ax1 = ax.twinx()
    
    # scale right axis labels to total samples and mutliply with 100 for percentages
    ax1.set_ylim(100*ymin/total_samples, 100*ymax/total_samples)
    
# Ensure good spacing  
g.fig.tight_layout()

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 2020-05-29
    • 2019-11-10
    • 1970-01-01
    相关资源
    最近更新 更多