简体   繁体   中英

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 . 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. It won't work that way. You were also adding 0.1 (a float) to x (a list) and hence the self-explanatory error. You have to loop over your Names and use the corresponding x and y value and put the text one name at a time. You can do it using enumerate as follows

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 . + 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM