【问题标题】:Can I color different months?我可以为不同的月份着色吗?
【发布时间】:2017-05-22 10:55:22
【问题描述】:

我的数据有一个日期时间索引。我已经对数据进行了重新采样并希望将其可视化,以便不同的月份都有不同的颜色。这是我的数据

Time        Count
2016-08-07  88
2016-08-14  95
2016-08-21  86
2016-08-28  81
2016-09-04  92
2016-09-11  89
2016-09-18  93
2016-09-25  83
2016-10-02  78
2016-10-09  90
2016-10-16  87
2016-10-23  79
2016-10-30  91
2016-11-06  90
2016-11-13  87
2016-11-20  97
2016-11-27  83
2016-12-04  63

如何绘制这些数据,以便每个月都有不同的颜色?

【问题讨论】:

  • 你使用bash终端吗?
  • 你想用什么样的情节?
  • 如果你想在 matplotlib 中绘制熊猫日期,试试这个:Plot pandas dates in matplotlib
  • @Bonifacio2 最好是条形图。我希望属于单独月份的每个条都具有相同的颜色(例如,所有 11 月的条都是蓝色的)

标签: python pandas


【解决方案1】:

这不适用于绘图(我已在下面添加),但如果您对此感兴趣,也可以为数据框文本输出着色。我发现它可以帮助我识别数据组。

我创建了一个新的 df['month'] 列,您可以在下面看到我应用的函数,以便使用 style 为您的月份添加颜色。

df['month'] = df.index.to_datetime().month

def color_monthd(val):

    color = 'blue' if val == 8\
    else 'orange' if val == 9\
    else 'purple' if val == 10\
    else 'red' if val == 11\
    else 'black'

    return 'color: %s' % color

s = df.style.applymap(color_monthd)

【讨论】:

    【解决方案2】:

    根据“属于单独月份的每个条形图都具有相同颜色”的要求。您可以在下面的字典中将颜色更改为您喜欢的任何颜色,然后在列表理解中使用这些颜色。

    df['month'] = df.index.to_datetime().month
    
    colors = {8: 'r', 9: 'b', 10: 'g',11: 'y', 12: 'w',}
    df['Count'].plot(kind='bar', color=[colors[i] for i in df['month']])
    

    【讨论】:

    • 我会添加 rot=45 以更好地查看 x 轴。
    猜你喜欢
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多