【问题标题】:Different colors in columns, Padas DataFrame列中的不同颜色,Pandas DataFrame
【发布时间】:2020-04-17 19:22:48
【问题描述】:

我有这样的 Pandas DataFrame:

data = pd.DataFrame({"fuel":["gas","gas","diesel","diesel","gas","diesel"]})

我用代码制作了条形图:

ax1 = data.fuel.value_counts().plot('bar')
ax1.set(xlabel = 'Fuel Type', ylabel='Frequency of fuel type')

尽管如此,我将两列放在一个颜色(蓝色)中。我应该怎么做才能有不同颜色的列?

【问题讨论】:

    标签: python pandas matplotlib colors


    【解决方案1】:

    你可以在plot()中设置颜色参数。

    import pandas as pd
    from matplotlib import pyplot as plt
    
    data = pd.DataFrame({"fuel":["gas","gas","diesel","diesel","gas","diesel"]})
    
    data.fuel.value_counts().plot('bar', color=['black', 'red'])
    ax1.set(xlabel = 'Fuel Type', ylabel='Frequency of fuel type')
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      data.fuel 的唯一值大小创建随机颜色列表,并将其传递给plot 的选项color

      colors = [np.random.uniform(size=3) for _ in  range(data.fuel.nunique())]
      ax1 = data.fuel.value_counts().plot('bar', color=colors)
      ax1.set(xlabel = 'Fuel Type', ylabel='Frequency of fuel type')
      

      【讨论】:

        猜你喜欢
        • 2018-04-16
        • 2016-09-23
        • 1970-01-01
        • 2017-11-13
        • 1970-01-01
        • 2021-11-22
        • 2016-02-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多