我在pandas dataframe中存储了一些数据。另外,我使用matplotlib创建显示数据的图。请看这张漂亮的照片:
红线显示与x轴点对应的一些值。它只是数据框中的一列。我想添加分类x轴点的其他注释。这些类别作为附加列存储在原始数据框中。它不必看起来像图片中那样。
目标是以某种方式显示x轴范围分类。添加这样的注释的智能和优雅方式是什么?
答案 0 :(得分:3)
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)
制作人物: