0

I am trying to plot datetime on x-axis and their values on the y-axis, and then draw vertical lines with different colors based on groups in a different column.

I am getting two errors.

  1. '0' key error - because of zeroes in C column
  2. AttributeError: 'AxesSubplot' object has no attribute 'vline'

input

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'} })
   

code

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)

1
  • `ax.vlines()` is collect. Commented Aug 8, 2020 at 5:15

1 Answer 1

1

The fixes are color.get() and ax.vlines for accessing the dictionary and drawing vertical lines.

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)

enter image description here

Sign up to request clarification or add additional context in comments.

7 Comments

How can change this to draw full vertical lines (of groups) instead of value range?
ax.vlines(df['A'][i], ymax=df['B'].max(), ymin=df['B'].min()) You can specify it like this.
what is x here?
That's because the minimum value is 1. So change it to ymin=0.
Did you run it with the new code? The ax.vlines(x, ymin,ymax)three data are required, and the third one, `ymax', is missing.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.