首页 > 解决方案 > 使用 Matplotlib 绘制带有日期时间的垂直线

问题描述

我试图datetime在 x 轴上绘制,在 y 轴上绘制它们的值,然后根据不同列中的组绘制不同颜色的垂直线。

我收到两个错误。

  1. '0' key error - 因为C列中的零
  2. 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)

标签: pythonmatplotlib

解决方案


修复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)

在此处输入图像描述


推荐阅读