Additional axis-like plot in matplotlib pandas plot

I store some data in a pandas dataframe. In addition, I use matplotlib to create graphs that display data. Look at this pretty picture:

plot i want

The red line shows some values โ€‹โ€‹corresponding to the x-axis points. This is just a column in the data area. I want to add an additional annotation classifying x-axis points. These categories are stored as additional columns in the original frame. It should not look like the picture.

The goal is to somehow show the categorization of the ranges of the x axis. What is a smart and elegant way to add such an annotation?

+4
1
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Create sample data
df = pd.DataFrame({'Data': [np.sin(i) + 3 for i in np.arange(1, 11, 0.1)],
                   'Annotation': ['A'] * 10 + ['B'] * 20 + [np.nan] * 10 +
                                 ['C'] * 10 + ['D'] * 10 + [np.nan] * 20 +
                                 ['D'] * 20})
# Get unique annotations
annotation_symbols = [i for i in df['Annotation'].unique() if not pd.isnull(i)]
# Transform each unique text annotation into a new column,
# where ones represent the corresponding annotation being 'active' and
# NaNs represent the corresponding annotation being 'inactive'
df = pd.concat([df, pd.get_dummies(df['Annotation']).replace(0, np.nan)])

plt.style.use('ggplot')  # Let use nicer style
ax = plt.figure(figsize=(7, 5)).add_subplot(111)
df.plot.line(x=df.index, y='Data', ax=ax)
df.plot.line(x=df.index, y=annotation_symbols, ax=ax)

:

enter image description here

+3

Source: https://habr.com/ru/post/1681709/


All Articles