【问题标题】:Set a different color to a row of dataframe为一行数据框设置不同的颜色
【发布时间】:2020-02-16 21:09:57
【问题描述】:

在下面的code 中,我们可以选择任意一对(name and age) 并制作它们的直方图:

将熊猫导入为 pd 将 matplotlib.pyplot 导入为 plt

df = pd.DataFrame({
    'name':['john','mary','peter','jeff','bill','lisa','jose'],
    'age':[23,78,22,19,45,33,20],
    'gender':['M','F','M','M','M','F','M'],
    'state':['california','dc','california','dc','california','texas','texas'],
    'num_children':[2,0,0,3,2,1,4],
    'num_pets':[5,1,0,5,2,2,3]
})
df.plot(kind='bar',x='name',y='age')
plt.show()

我想要做的是将 Lisa 的栏设置为红色,其余部分保持不变。

如何设置某一行的颜色?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    看着docs of df.plot()

    DataFrame.plot(x=None, y=None, kind='line', ax=None, subplots=False, sharex=None, sharey=False, layout=None, figsize=None, use_index=True, 标题=无,网格=无,图例=真,样式=无,logx=假, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None, rot=None, fontsize=None, colormap=None, table=False, yerr=None,xerr=None,secondary_y=False,sort_columns=False, **kwds)

    我们可以看到该函数采用**kwds(引号的最后一行)

    进一步看:

    [...] **kwds : 关键字 传递给 matplotlib 绘图方法的选项

    你调用的绘图方法是plt.bar(),其documentation说:

    Other Parameters: 
        color : scalar or array-like, optional
        The colors of the bar faces.
    
        edgecolor : scalar or array-like, optional
        The colors of the bar edges.
    

    因此,您可以将所需颜色的列表或数组传递给该方法,如下所示:

    color = 7*['blue']
    color[-2] = 'red'
    
    df.plot(kind='bar',x='name',y='age', color=color)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 2011-12-05
      • 2012-02-27
      • 2017-11-09
      • 2019-05-22
      相关资源
      最近更新 更多