1

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)
2
  • The error is not with text, it's with x+0.1 and y+0.1, which you would be more aware of if you processed and posted the whole error Commented Sep 25, 2018 at 11:34
  • The error was with trying to use all Names at once in plt.text and adding 0.1 to x and y which are of type list Commented Sep 25, 2018 at 11:41

2 Answers 2

2

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)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Perhaps you should add +0.1 to x_ and y_ to avoid the text overlapping the markers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.