python - matplotlib Pandas 图中的附加 "axis like"图

标签 python pandas matplotlib dataframe plot

我正在将一些数据存储在 pandas 数据框中。此外,我正在使用 matplotlib 创建显示数据的图表。请看这张漂亮的图片:

plot I want

红线表示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)

生成图:

enter image description here

关于python - matplotlib Pandas 图中的附加 "axis like"图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45169178/

相关文章:

python - 帮助使用 Python 2.6 中的 cPickle

Python:subprocess.stdin.write 无法正常工作

python - 迭代更改 Pandas 数据框列中的每个单元格

python - Python 的 Matplotlib 模块的奇怪行为 - 绘制圆

python - 如何使用 pandas 和 matplotlib 生成离散数据以传递到等高线图?

python - 我可以在 python 中加载 python 代码并将其解析为普通代码行吗?

使用 pip 安装时 Python 包散列不匹配

Python:检查每个用户的唯一类别

python - 如果元素等于数据帧 B 中的元素,则从数据帧 A 中删除行的有效方法

python - 热图未加载 seaborn 和 pandas 数据框