【问题标题】:How to color bars based on a separate pandas column如何根据单独的熊猫列着色条
【发布时间】:2021-10-06 20:49:26
【问题描述】:

我需要根据数据框的“属性”列绘制条形图并应用颜色

x 轴 = 共享
y轴=价格

fig, ax = plt.subplots()
ax.barh(df['Share'],df['Price'], align='center')
ax.set_xlabel('Shares')
ax.set_ylabel('Price')
ax.set_title('Bar Chart & Colors')
plt.show()

感谢您的帮助!

【问题讨论】:

    标签: python pandas matplotlib seaborn bar-chart


    【解决方案1】:
    • 有两种简单的方法可以为'Attribute' 绘制不同颜色的条形图
      1. 使用.pivot 转换数据框,然后使用pandas.DataFrame.plot 进行绘图,并指定kind='barh' 用于水平条形图
        • 如果使用kind='bar',索引将是x轴,如果使用kind='barh',索引将是y轴
        • 转换后的数据框的每列都将使用单独的颜色进行绘制。
        • pandas 使用 matplotlib 作为默认的绘图后端。
      2. seaborn.barplothue='Attribute'orient='h' 一起使用。此选项适用于长格式的数据帧,如 OP 中所示。
        • seabornmatplotlib 的高级 API
    • 使用pandas 1.3.0seaborn 0.11.1matplotlib 3.4.2 测试

    导入和数据帧

    import pandas as pd
    import seaborn as sns
    
    # test dataframe
    data = {'Price': [110, 105, 119, 102, 111, 117, 110, 110], 'Share': [110, -50, 22, 79, 29, -2, 130, 140], 'Attribute': ['A', 'B', 'C', 'D', 'A', 'B', 'B', 'C']}
    df = pd.DataFrame(data)
    
       Price  Share Attribute
    0    110    110         A
    1    105    -50         B
    2    119     22         C
    3    102     79         D
    4    111     29         A
    5    117     -2         B
    6    110    130         B
    7    110    140         C
    

    pandas.DataFrame.plot

    # transform the dataframe with .pivot
    dfp = df.pivot(index='Price', columns='Attribute', values='Share')
    
    Attribute      A      B      C     D
    Price                               
    102          NaN    NaN    NaN  79.0
    105          NaN  -50.0    NaN   NaN
    110        110.0  130.0  140.0   NaN
    111         29.0    NaN    NaN   NaN
    117          NaN   -2.0    NaN   NaN
    119          NaN    NaN   22.0   NaN
    
    # plot
    ax = dfp.plot(kind='barh', title='Bar Chart of Colors', figsize=(6, 4))
    ax.set(xlabel='Shares')
    ax.legend(title='Attribute', bbox_to_anchor=(1, 1), loc='upper left')
    ax.grid(axis='x')
    

    • stacked=True
    ax = dfp.plot(kind='barh', stacked=True, title='Bar Chart of Colors', figsize=(6, 4))
    

    seaborn.barplot

    • 请注意,与上一个图相比,y 轴值的顺序颠倒了
    ax = sns.barplot(data=df, x='Share', y='Price', hue='Attribute', orient='h')
    ax.set(xlabel='Shares', title='Bar Chart of Colors')
    ax.legend(title='Attribute', bbox_to_anchor=(1, 1), loc='upper left')
    ax.grid(axis='x')
    

    【讨论】:

    • 感谢非常有用!是否可以在价格水平和颜色分割上进行聚合?例如,如果我有 1 个价格、3 个股票级别和 3 个属性,我想创建一个柱而不是创建 3 个柱(已完成)
    • @MinatoDBO 您可以将stacked=Truedf.plot 一起使用。但是,我不建议使用堆叠条,因为它们更难以比较值。
    • 好的,非常感谢,请给我最后一个问题!是否可以添加水平线?我试着做 ax.hlines(y=117, xmin=-50, xmax=125, linewidth=2, color='r') 但没有用
    • @MinatoDBO 条形图实际上并未按显示的数字索引。他们解决了位置(例如 0、1、2、3、...)。所以你可以做ax.hlines(y=4, xmin=-50, xmax=125, linewidth=2, color='r')。如果答案是有益的,除了接受它,您还可以为答案投票。
    猜你喜欢
    • 2021-12-14
    • 2020-03-17
    • 2017-11-07
    • 1970-01-01
    • 2019-11-12
    • 2021-08-27
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多