【问题标题】:Seaborn countplot with second axis with ordered dataSeaborn countplot 与第二轴与有序数据
【发布时间】:2020-01-02 11:56:07
【问题描述】:

我正在尝试创建一个带有线图的计数图,作为我将在工作中进行的一些数据可视化的练习。我正在查看 kaggle 上的 kickstarter 数据Link here

我在项目状态(成功、失败、取消)上运行了一个带有色调的计数图,并且这两个都是有序的

filter_list = ['failed', 'successful', 'canceled']
df2 = df[df.state.isin(filter_list)]

fig = plt.gcf()
fig.set_size_inches( 16, 10)
sns.countplot(x='main_category', hue='state', data=df2, order = df2['main_category'].value_counts().index, 
              hue_order = df2['state'].value_counts().index)

结果如下:

然后我创建第二个轴并添加线图

fig, ax = plt.subplots()
fig.set_size_inches( 16, 10)

ax = sns.countplot(x='main_category', hue='state', data=df, ax=ax, order = df2['main_category'].value_counts().index, 
              hue_order = df2['state'].value_counts().index)

ax2 = ax.twinx()
sns.lineplot(x='main_category', y='backers', data=df2, ax =ax2)

但这会改变列标签,如下所示:

看起来数据是相同的,只是列的顺序不同。我仍在学习,所以我的代码可能效率低下或其中一些是多余的,但任何帮助将不胜感激。唯一的其他事情是如何创建 df,如下所示:

import pandas as pd
import numpy as np
import seaborn as sns; sns.set(style="white", color_codes=True)
import matplotlib.pyplot as plt

df = pd.read_csv('ks.csv')
df = df.drop(['ID'], axis = 1)
df.head()

【问题讨论】:

    标签: python python-3.x matplotlib data-visualization seaborn


    【解决方案1】:

    我认为lineplot 不是您要找的。 lineplot 应该使用 with numeric data,而不是分类。我什至很惊讶这完全有效。

    我认为您正在寻找pointplot

    filter_list = ['failed', 'successful', 'canceled']
    df2 = df[df.state.isin(filter_list)]
    order = df2['main_category'].value_counts().index
    
    fig = plt.figure()
    ax1 = sns.countplot(x='main_category', hue='state', data=df2, order=order, 
                  hue_order=filter_list)
    ax2 = ax1.twinx()
    sns.pointplot(x='main_category', y='backers', data=df2, ax=ax2, order=order)
    

    请注意,这样使用时,pointplot 将显示各个类别的平均支持者数量。如果这不是您想要的,您可以使用 estimator= 参数传递另一个聚合函数

    例如

    sns.pointplot(x='main_category', y='backers', data=df2, ax=ax2, order=order, estimator=np.sum)
    

    【讨论】:

    • 非常感谢,这很有帮助,我仍在学习这些可视化,所以最好找出我哪里出错了
    猜你喜欢
    • 2020-07-12
    • 2018-05-15
    • 2023-04-07
    • 1970-01-01
    • 2017-07-22
    • 2023-01-23
    • 2023-03-19
    • 2019-12-27
    • 1970-01-01
    相关资源
    最近更新 更多