【问题标题】:Plot area charts with different colors for time series data based on multiple condtions in MatplotlibMatplotlib中基于多个条件的时间序列数据绘制不同颜色的面积图
【发布时间】:2021-11-12 05:48:27
【问题描述】:

给定一个小数据集如下:

         date  value  type
0  2021-07-31   6.32     1
1  2021-08-31   5.93     1
2  2021-09-30   5.43     2
3  2021-10-30   4.72     2
4  2021-11-30   4.23     3
5  2021-12-31   3.96     3

或:

df = pd.DataFrame({'date': {0: '2021-07-31',
  1: '2021-08-31',
  2: '2021-09-30',
  3: '2021-10-30',
  4: '2021-11-30',
  5: '2021-12-31'},
 'value': {0: 6.32, 1: 5.93, 2: 5.43, 3: 4.72, 4: 4.23, 5: 3.96},
 'type': {0: 1, 1: 1, 2: 2, 3: 2, 4: 3, 5: 3}})

我希望根据type绘制面积图,即日期如果type=1, 2, 3,我将分别使用颜色graylightpinkskyblue

我怎么能这样做?谢谢。

预期的情节是这样的:

参考代码:

year_n_1 = [1.5, 3, 10, 13, 22, 36, 30, 33, 24.5, 15, 6.5, 1.2]
year_n = [2, 7, 14, 17, 20, 27, 30, 38, 25, 18, 6, 1]

plt.fill_between(np.arange(12), year_n_1, color="lightpink",
                 alpha=0.5, label='year N-1')
plt.fill_between(np.arange(12), year_n, color="skyblue",
                 alpha=0.5, label='year N')

plt.legend()
plt.show()

输出:

编辑:

df = df.set_index('date')
colors = ['gray', 'lightpink', 'skyblue']
plt.fill_between(df['value'], color=colors[type], alpha=0.5)
plt.legend()
plt.show()

输出:

TypeError: list indices must be integers or slices, not type

【问题讨论】:

  • 不完全清楚你想要做什么,你想要每天的条形图有不同的颜色,还是像你的例子中的区域?数据如何与您的示例相关联?在尝试解决方案方面,您是否可以不只是拥有您引用的颜色的listdictionary?像colors = ['gray', 'lightpink', 'skyblue'] 这样的东西,然后在你的绘图命令中,color=colors[type]
  • 与示例图略有不同,因为我的数据是时间序列,所以我希望将它绘制在三个不同颜色的区域图表上,x 轴是date。请查看编辑代码。
  • 我在问题中添加了一个预期的情节,请检查。
  • 您好,fill_between 函数不能这样工作,请阅读matplotlib.org/stable/api/_as_gen/…。您的错误是由于 color 是一个列表而 type 是一个字符串并且不能用字符串切片或索引列表。你应该把它放在一个 for 循环中并调用类似 colors[i] where i: 0,1,2.

标签: python-3.x matplotlib


【解决方案1】:

试试:

# let's use datetime type 
df['date'] = pd.to_datetime(df['date'])

# the colors
colors = ['gray', 'lightpink', 'skyblue']

# loop and plot
fig, ax = plt.subplots()
for i, (t, d) in enumerate(df.groupby('type')):
    d.plot.area(x='date', y='value', label=t, ax=ax, alpha=0.5, color=colors[i])
    
plt.show()

输出:

【讨论】:

猜你喜欢
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-09
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多