在 pandas 散点图中注释标签
Annotate labels in pandas scatter plot
我从旧的 post 那里看到了这个方法,但无法得到我想要的情节。
开始
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]))
散点图
ax = df.plot('x','y', kind='scatter', s=50)
然后定义一个函数来迭代要注释的行
def annotate_df(row):
ax.annotate(row.name, row.values,
xytext=(10,-5),
textcoords='offset points',
size=18,
color='darkslategrey')
最后一次申请获得注释
ab= df.apply(annotate_df, axis=1)
不知何故,我得到了一个系列 ab 而不是我想要的散点图。哪里错了?谢谢!
您的代码有效,您只需要在末尾添加 plt.show()。
您的完整代码:
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]))
ax = df.plot('x','y', kind='scatter', s=50)
def annotate_df(row):
ax.annotate(row.name, row.values,
xytext=(10,-5),
textcoords='offset points',
size=18,
color='darkslategrey')
ab= df.apply(annotate_df, axis=1)
plt.show()
看起来这不再有效,但解决方案很简单:将 row.values 从 numpy.ndarray 转换为列表:
list(row.values)
我从旧的 post 那里看到了这个方法,但无法得到我想要的情节。
开始
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]))
散点图
ax = df.plot('x','y', kind='scatter', s=50)
然后定义一个函数来迭代要注释的行
def annotate_df(row):
ax.annotate(row.name, row.values,
xytext=(10,-5),
textcoords='offset points',
size=18,
color='darkslategrey')
最后一次申请获得注释
ab= df.apply(annotate_df, axis=1)
不知何故,我得到了一个系列 ab 而不是我想要的散点图。哪里错了?谢谢!
您的代码有效,您只需要在末尾添加 plt.show()。
您的完整代码:
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]))
ax = df.plot('x','y', kind='scatter', s=50)
def annotate_df(row):
ax.annotate(row.name, row.values,
xytext=(10,-5),
textcoords='offset points',
size=18,
color='darkslategrey')
ab= df.apply(annotate_df, axis=1)
plt.show()
看起来这不再有效,但解决方案很简单:将 row.values 从 numpy.ndarray 转换为列表:
list(row.values)