matplotlib - 从 Pandas DataFrame 绘图时注释数据点

标签 matplotlib pandas

我想在绘图上的点旁边标注数据点的值。我发现的例子仅将 x 和 y 作为向量处理。但是,我想对包含多列的 pandas DataFrame 执行此操作。

ax = plt.figure().add_subplot(1, 1, 1)
df.plot(ax = ax)
plt.show()

注释多列 DataFrame 的所有点的最佳方法是什么?

最佳答案

这是 Dan Allan's answer 的(非常)稍微平滑的版本:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import string

df = pd.DataFrame({'x':np.random.rand(10), 'y':np.random.rand(10)}, 
                  index=list(string.ascii_lowercase[:10]))

这给出:

          x         y
a  0.541974  0.042185
b  0.036188  0.775425
c  0.950099  0.888305
d  0.739367  0.638368
e  0.739910  0.596037
f  0.974529  0.111819
g  0.640637  0.161805
h  0.554600  0.172221
i  0.718941  0.192932
j  0.447242  0.172469

然后:

fig, ax = plt.subplots()
df.plot('x', 'y', kind='scatter', ax=ax)

for k, v in df.iterrows():
    ax.annotate(k, v)

最后,如果您处于交互模式,您可能需要刷新绘图:

fig.canvas.draw()

它产生: Boring scatter plot

或者,因为这看起来非常丑陋,你可以很容易地美化一些东西:

from matplotlib import cm
cmap = cm.get_cmap('Spectral')
df.plot('x', 'y', kind='scatter', ax=ax, s=120, linewidth=0, 
        c=range(len(df)), colormap=cmap)

for k, v in df.iterrows():
    ax.annotate(k, v,
                xytext=(10,-5), textcoords='offset points',
                family='sans-serif', fontsize=18, color='darkslategrey')

看起来好多了: Nice scatter plot

关于matplotlib - 从 Pandas DataFrame 绘图时注释数据点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15910019/

相关文章:

python - 在使用seaborn时的jointplot中,如何在图中设置另一个图例

python - matplotlib 在 3D 中绘制多条线

python - 使用第三列值将颜色渐变映射到第 1 列和第 2 列的图; Matplotlib

python - 如果 Pandas 中月份差异超过 1,如何按排名分组并开始新的排名?

python - 在创建 DataFrame 时保持列顺序

python - 在 Jupyter notebook 下方显示新的 matplotlib 图

python - 如何使用 python 和 matplotlib 将页码添加到 PDF 文件?

python - 如何根据一列的字符串相似度链接两个数据框

python - 使用千位分隔符格式化多个数据框列

python - 你如何通过 Pandas 替换功能传递字典?