[英]Using matplotlib to plot text
I'm trying to put text in a graph, but for some reason I can't do it using plt.text
. 我正在尝试将文本放在图形中,但是由于某些原因,我无法使用plt.text
做到这plt.text
。 I get the 我得到了
TypeError: can only concatenate list ("not float") to list
I don't really know what to change to get this working. 我真的不知道该进行哪些更改才能使其正常工作。
x = [3, 1, 4, 5, 1]
y = [5, 4, 4, 3, 7]
fig=plt.figure(1)
ax = fig.add_subplot(1, 1, 1)
plt.xlim(0.5, 7)
plt.ylim(0, 7.5)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.scatter(x, y, marker="x", color="red")
Names=['name1', 'name2', 'name3', 'name4', 'name4']
plt.text(x + 0.1, y + 0.1, Names, fontsize=9)
You are trying to use plt.text
in a vectorised manner. 您正在尝试以向量化方式使用plt.text
。 It won't work that way. 这样就行不通了。 You were also adding 0.1
(a float) to x
(a list) and hence the self-explanatory error. 您还向x
(列表)添加了0.1
(浮点数),因此产生了不言自明的错误。 You have to loop over your Names
and use the corresponding x
and y
value and put the text
one name at a time. 您必须遍历“ Names
并使用相应的x
和y
值,并一次将一个text
一个名称。 You can do it using enumerate
as follows 您可以使用enumerate
以下操作
Names=['name1', 'name2','name3','name4','name4']
for i, name in enumerate(Names):
plt.text(x[i]+0.1, y[i]+0.1, name, fontsize=9)
There are two errors in your code. 您的代码中有两个错误。
The one that is raising is that you attempt to add a scalar to a Python list: x + 0.1
and y + 0.1
. 提出的一个问题是您尝试向Python列表添加标量: x + 0.1
和y + 0.1
。 +
is defined as concatenation, which is what the error is telling you. +
定义为串联,这就是错误告诉您的内容。 You can potentially fix this by converting x
and y
to numpy arrays ahead of time. 您可以通过提前将x
和y
转换为numpy数组来解决此问题。 For arrays, +
is defined as element-wise addition, as you were expecting. 正如您所期望的,对于数组, +
定义为逐元素加法。 However, this won't solve your second problem. 但是,这不会解决您的第二个问题。
The documentation for pyplot.text
explicitly states that the x
and y
inputs are scalars: you can only plot one string per call. pyplot.text
的文档明确指出x
和y
输入为标量:每个调用只能绘制一个字符串。 That means you need a loop: 这意味着您需要一个循环:
for x_, y_, name in zip(x, y, Names):
plt.text(x_ + 0.1, y_ + 0.1, name, fontsize=9)
Please read your errors carefully and post the whole thing next time. 请仔细阅读您的错误,并在下次发布完整内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.