【问题标题】:Label points in dataframe Python数据框Python中的标签点
【发布时间】:2018-01-22 15:36:06
【问题描述】:

我想用 x 轴值标记 pandas 中的数据点。我正在尝试将此解决方案应用到我的代码中:Annotate data points while plotting from Pandas DataFrame

我收到一条错误消息:

AttributeError: 'PathCollection' object has no attribute 'text'

这是我的代码:

def draw_scatter_plot(xaxis, yaxis, title, xaxis_label, yaxis_label, save_filename, color, figsize=(9, 7), dpi=100):
    fig = plt.figure(figsize=figsize, dpi=dpi)

    ax = plt.scatter(xaxis, yaxis, c=color)

    plt.xlabel(xaxis_label)
    plt.ylabel(yaxis_label)

    label_point(xaxis, yaxis, xaxis, ax)

    plt.title(title)

    fig.savefig(save_filename, dpi=100)

# label code from https://stackoverflow.com/questions/15910019/annotate-data-points-while-plotting-from-pandas-dataframe/15911372#15911372

def label_point(x, y, val, ax):
    a = pd.concat({'x': x, 'y': y, 'val': val}, axis=1)
    for i, point in a.iterrows():
        ax.text(point['x'], point['y'], str(point['x']))

对这个问题有什么建议吗?

【问题讨论】:

  • Pandas 的绘图返回一个坐标轴对象docs。您使用 plt.scatter,它返回一个路径对象docs
  • @sascha 哦,明白了。如何在这里应用注释功能?
  • 手动创建一个轴对象,用它来调用分散,然后将它传递给你的标签函数。我不确定最佳做法是什么,但f, ax = plt.subplots(1) 后跟ax.scatter()(可能是ax[0]))可能会起作用。 (虽然它看起来很傻,因为 subplots
  • @sascha 我已按照指导修复了代码。但它什么也没显示。
  • 那么您可能应该显示您修改后的代码。 编辑: 或使用 MaxU 更聪明的方法!

标签: python pandas matplotlib


【解决方案1】:

考虑以下演示:

In [6]: df = pd.DataFrame(np.random.randint(100, size=(10, 2)), columns=list('xy'))

In [7]: df
Out[7]:
    x   y
0  44  13
1  69  53
2  52  80
3  72  64
4  66  42
5  96  33
6  31  13
7  61  81
8  98  63
9  21  95

In [8]: ax = df.plot.scatter(x='x', y='y')

In [9]: df.apply(lambda r: ax.annotate(r['x'].astype(str)+'|'+r['y'].astype(str), 
                                       (r.x*1.02, r.y*1.02)), axis=1)
Out[9]:
0    Annotation(44,13,'44|13')
1    Annotation(69,53,'69|53')
2    Annotation(52,80,'52|80')
3    Annotation(72,64,'72|64')
4    Annotation(66,42,'66|42')
5    Annotation(96,33,'96|33')
6    Annotation(31,13,'31|13')
7    Annotation(61,81,'61|81')
8    Annotation(98,63,'98|63')
9    Annotation(21,95,'21|95')
dtype: object

结果:

【讨论】:

  • matplotlib 和 pandas 的完美结合!
【解决方案2】:

问题出现是因为您将plt.scatter 的返回名称命名为ax。这令人困惑,因为它不是轴,而是'PathCollection'(正如错误告诉您的那样)。

替换前两行

fig = plt.figure(figsize=figsize, dpi=dpi)
ax = plt.scatter(xaxis, yaxis, c=color)

fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
ax.scatter(xaxis, yaxis, c=color)

并保持其余代码相同。

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 2014-09-08
    • 1970-01-01
    • 2017-09-20
    • 2019-04-27
    • 1970-01-01
    • 2019-09-15
    • 2017-01-27
    • 1970-01-01
    相关资源
    最近更新 更多