Pandas 在散点图中注释标签

Pandas 在散点图中注释标签,pandas,plot,annotate,Pandas,Plot,Annotate,我在一篇老文章中看到了这种方法,但无法得到我想要的情节 开始 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])) 散点图 a

我在一篇老文章中看到了这种方法,但无法得到我想要的情节

开始

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()

代码正常工作,最后只需要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:

list(row.values)

看起来这不再有效,但是解决方案很简单:将row.values从numpy.ndarray转换为list:

list(row.values)

顺便问一下,有没有办法解决注释过多的重叠问题?看看这里:顺便问一下,有没有办法解决注释过多的重叠问题?看看这里: