python - 通过传递列表/元组更改 Pandas matplotlib 条形图中的条形颜色

标签 python pandas matplotlib

关于这个主题有几个线程,但它们似乎都没有直接解决我的问题。我想使用不依赖于 map 的自定义配色方案从 Pandas 数据框中绘制条形图,例如使用任意颜色列表。看起来我可以传递一个带有颜色速记名称的串联字符串(下面的第一个示例)。当我使用建议时 here ,重复第一种颜色(参见下面的第二个示例)。那个帖子中有一条评论与我观察到的行为相同。当然,我可以通过设置子图来做到这一点,但我很懒,想在一行中完成。所以,我想使用最后一个例子,我传入一个十六进制代码列表,它按预期工作。我正在使用 Pandas 版本 >=0.24 和 matplotlib 版本 >1.5。我的问题是:

  • 为什么会发生这种情况?
  • 我究竟做错了什么?
  • 我可以传递颜色列表吗?
  • pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color="brgmk" )
    
    enter image description here
    pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[ "b", "r", "g", "m", "k" ] )
    
    enter image description here
    pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[ "#0000FF", "#FF0000", "#008000", "#FF00FF", "#000000" ] )
    
    enter image description here

    最佳答案

    绘制数据框时,第一个颜色信息用于第一列,第二个用于第二列等。颜色信息可能只是一个值,然后用于该列的所有行,或者使用多个值 -对列的每一行逐一(如果行数多于颜色,则从头开始重复)。请参阅以下示例:

    pd.DataFrame( [[ 1, 4], [2, 5], [3, 6]] ).plot(kind="bar", color=[[ "b", "r", "g" ], "m"] )
    
    enter image description here
    因此,在您的情况下,您只需要将颜色值列表放在列表中(特别是不是元组):
    pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[[ "b", "r", "g", "m", "k" ]] )
    
    或者
    pd.DataFrame( [ 1, 2, 3, 4, 5 ] ).plot( kind="bar", color=[[ "#0000FF", "#FF0000", "#008000", "#FF00FF", "#000000" ]] )
    

    OP 中的第一个案例 ( color="brgmk" ) 与 pandas internally puts the color string in a list 一样按预期工作( strings are not considered list-like )。

    关于python - 通过传递列表/元组更改 Pandas matplotlib 条形图中的条形颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62826624/

    相关文章:

    python - 如何用行中的前一个可用值填充 nan 值?

    python - 如何使用 Pandas 创建这个数据框?

    python - 如何使用 Axes3D 显示我的曲面图?

    python - 类型错误 : histogram() got an unexpected keyword argument 'new'

    python - 向 matplotlib/seaborn 图中的某些单元格添加自定义边框

    python - 如何在不损坏文件的情况下使用 AES 和 pycrypto 加密 .docx 文件

    python - 在 Python 中与 Pandas 进行大型合并时出现 MemoryError

    python - 在函数中使用 groupby 组名

    python - Django——更改时的表单字段

    python - Scikit Learn 使用随机森林的分类数据