python - 使用 Matplotlib 绘制带有日期时间的垂直线
问题描述
我试图datetime
在 x 轴上绘制,在 y 轴上绘制它们的值,然后根据不同列中的组绘制不同颜色的垂直线。
我收到两个错误。
'0' key error
- 因为C
列中的零AttributeError: 'AxesSubplot' object has no attribute 'vline'
输入
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
df = pd.DataFrame({'A': {0: '2020-01-01 06:00:00',
1: '2020-01-01 18:00:00',
2: '2020-01-02 06:00:00',
3: '2020-01-02 18:00:00',
4: '2020-01-03 06:00:00',
5: '2020-01-03 18:00:00',
6: '2020-01-04 06:00:00',
7: '2020-01-04 18:00:00'},
'B': {0: 5, 1: 5, 2: 6, 3:6, 4:7, 5:7, 6:1, 7:1},
'C': {0:'group1', 1:'group1', 2:'group2', 3:'group2', 4:'group3', 5:'group3', 6:'0', 7:'0'} })
代码
fig, ax = plt.subplots(1)
colors = {0:'w','group1': 'r', 'group2': 'yellow', 'group3': 'grey'}
ax.vline(df['A'],df['B'], color=[colors[i] for i in df['C']])
ax.bar(df['A'], df['B'], linestyle='-',color='midnightblue' ,lw=6, width=0.01)
解决方案
修复color.get()
和ax.vlines
用于访问字典和绘制垂直线。
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1)
colors = {'0':'w','group1': 'r', 'group2': 'yellow', 'group3': 'grey'}
for i in range(len(df)):
v = colors.get(df['C'][i])
ax.vlines(df['A'][i], 0, df['B'].max(), color=v)
ax.bar(df['A'], df['B'], linestyle='-', color='midnightblue', lw=6, width=0.01)
推荐阅读
- javascript - 打字稿:定义对象键值的返回
- github - 分叉的存储库会从被阻止的 github 用户中删除吗?
- haskell - 用haskell中的选定字符拆分字符串
- c - 使用 malloc 和 calloc 创建二维数组
- node.js - Node.js websockets 客户端-服务器数据包
- scala - 如何对猫进行平面映射
- c++ - typename c++ 和编译顺序
- python - Django 设置 DigitalOchean Postgre "DATABASES = {" ERORR
- python - Pygame中的墙逻辑
- react-native - React Native Linking to web page and push back button