我想在绘图上的点旁边标注数据点的值。我发现的例子仅将 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()
它产生:
或者,因为这看起来非常丑陋,你可以很容易地美化一些东西:
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')
看起来好多了:
关于matplotlib - 从 Pandas DataFrame 绘图时注释数据点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15910019/