我正在尝试在x轴上绘制datetime
,并在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)
答案 0 :(得分:1)
修复方法为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)