[英]TypeError when adding text to matplotlib plot
I have a csv file that shows some references and their coordinates for some electronic parts:我有一个 csv 文件,其中显示了一些电子零件的一些参考及其坐标:
I've been working about drawing rectangles for these references using matplotlib.pyplot
, matplotlib.patches
and Rectangle
:我一直在使用
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)
I decided to create rectangles for these coordinates and set their "Part ID" from the csv file as their names using plt.text
:我决定为这些坐标创建矩形,并使用
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)
(I randomly chose 200 as width and 300 as height. Don't mind that.) (我随机选择了 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')
In plt.text
row, i tried to name the Rectangles with their Part ID from the csv file.在
plt.text
行中,我尝试使用 csv 文件中的部件 ID 命名矩形。 I created a variable z
and set the names to z
as string.我创建了一个变量
z
并将名称设置为z
作为字符串。 The exact problem starts here:确切的问题从这里开始:
When i started to run the program, all of the code works fine without naming them as their Part ID.当我开始运行程序时,所有代码都可以正常工作,而无需将它们命名为 Part ID。
After this drawing, i decided to add the plt.text
row for naming them.在这张图之后,我决定添加
plt.text
行来命名它们。
But i get the error: TypeError: text() missing 1 required positional argument: 's'
但我收到错误:
TypeError: text() missing 1 required positional argument: 's'
There is a problem about string assigning in plt.text(.....%s)
. plt.text(.....%s)
中的字符串分配存在问题。 Is there anyone that knows what to do?有没有人知道该怎么做?
How can i assign each of them their Part ID names?我怎样才能给他们每个人分配他们的零件 ID 名称?
The call signature for plt.text
is: plt.text
的调用签名是:
plt.text(x, y, s, ...)
Note that x
, y
, and s
are all arguments to this function.注意
x
、 y
和s
都是 arguments 到这个 function。
You have used:您使用过:
plt.text((df['X'][n], df['Y'][n]), 'ID: %s' % (z_n))
where you have given the x, y coordinates as the tuple (df['X'][n], df['Y'][n])
.您已将 x, y 坐标作为元组
(df['X'][n], df['Y'][n])
给出。 Remove the parentheses from around them, and it should work just fine:从它们周围删除括号,它应该可以正常工作:
plt.text(df['X'][n], df['Y'][n], 'ID: %s' % (z_n))
Better yet, to make sure you are giving the correct arguments to the function, you could name the arguments:更好的是,为了确保您将正确的 arguments 提供给 function,您可以将 arguments 命名为:
plt.text(x=df['X'][n], y=df['Y'][n], s='ID: %s' % (z_n))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.