我正在将一些数据存储在 pandas 数据框中。此外,我正在使用 matplotlib 创建显示数据的图表。请看这张漂亮的图片:
红线表示x轴点对应的一些值。它只是数据框中的一列。我想添加额外的注释来分类 x 轴点。这些类别存储为原始数据框中的附加列。它不必看起来与图片中的完全一样。
目标是以某种方式显示 x 轴范围分类。添加此类注释的聪明而优雅的方法是什么?
最佳答案
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)
生成图:
关于python - matplotlib Pandas 图中的附加 "axis like"图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45169178/