【问题标题】:TypeError when adding text to matplotlib plot将文本添加到 matplotlib 图中时出现 TypeError
【发布时间】:2020-08-20 19:08:10
【问题描述】:

我有一个 csv 文件,其中显示了一些电子零件的参考及其坐标:

我一直在使用matplotlib.pyplot、matplotlib.patches 和Rectangle 为这些引用绘制矩形:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from patches import Rectangle

fig = plt.figure()
ax = fig.add_subplot(111)

我决定为这些坐标创建矩形,并使用 plt.text 将 csv 文件中的“零件 ID”设置为它们的名称:

n=0

for n in range(30):
    z = df['Part ID'][n]
    rect_n = patches.Rectangle((df['X'][n], df['Y'][n]), 200, 300, fill = False)

(我随机选择宽度为 200,高度为 300。不要介意。)

for n in range(30):
    z_n = df['Part ID'][n]
    rect_n = patches.Rectangle((df['X'][n], df['Y'][n]), 200, 300, fill = False)
    ax.add_patch(rect_n)
    plt.text((df['X'][n], df['Y'][n]), 'ID: %s' % (z_n))

df.plot(kind='scatter', x='X', y='Y', ax=ax)
ax.set_axisbelow(True)
ax.grid(linestyle='-', linewidth='2', color='g')

在plt.text 行中,我尝试使用 csv 文件中的部件 ID 命名矩形。我创建了一个变量z 并将名称设置为z 作为字符串。 确切的问题从这里开始:

当我开始运行程序时,所有代码都可以正常工作,而无需将它们命名为 Part ID。

在这幅画之后,我决定添加plt.text 行来命名它们。

但我得到了错误:TypeError: text() missing 1 required positional argument: 's'

plt.text(.....%s) 中的字符串分配存在问题。有谁知道该怎么做?

我如何为每个人分配其零件 ID 名称?

【问题讨论】:

标签: python pandas string csv matplotlib


【解决方案1】:

plt.text 的调用签名是:

plt.text(x, y, s, ...)

请注意,x、y 和 s 都是此函数的参数。

您使用过:

plt.text((df['X'][n], df['Y'][n]), 'ID: %s' % (z_n))

您已将 x、y 坐标作为元组 (df['X'][n], df['Y'][n]) 给出。从它们周围删除括号,它应该可以正常工作:

plt.text(df['X'][n], df['Y'][n], 'ID: %s' % (z_n))

更好的是,为了确保您为函数提供正确的参数,您可以命名参数:

plt.text(x=df['X'][n], y=df['Y'][n], s='ID: %s' % (z_n))

【讨论】:

  • 非常感谢!我没有考虑单独分配 x,y,s。我认为逗号足以分隔,但我错了。再次感谢,祝您有美好的一天!
猜你喜欢
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 2016-04-28
  • 2016-09-16
  • 2019-09-17
相关资源
最近更新 更多