I am storing some data in pandas dataframe. Also, I am using matplotlib to create plots showing the data. Please look at this pretty picture:
Red line shows some values corresponding to x axis points. It is just a column in the dataframe. I want to add additional annotation categorizing x axis points. Those categories are stored as additional columns in the original dataframe. It does not have to look exactly like in the picture.
The goal is to somehow show x axis ranges categorization. What is a smart and elegant way to add such an annotation?
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's 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)
Produced figure:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.