0

I am trying to plot views by post (vbyp list) using matplotlib.plt() and using a names list to add text at each point. But, the annotate function keeps show the error :

x, y = xytext
TypeError: 'float' object is not iterable

To rectify it I have used the range() method but it doesn't correct it.

import matplotlib.pyplot as plt

names = ['S','Deuk','Cip','Pubt','Adoct','Vsa','Rener',
'Gols','OYO','Qum','Sre','Mey','Micft',
'Nia','Tco','Texments','Fidty','Jrgan','Adoch','MyKa','Dw','Ba','HL','Nx','Towerch','Uer']
posts = [6,3,4,4,6,3,3,8,7,2,15,4,5,5,2,2,2,5,3,2,2,3,4,1,1,1]
views =[554,1272,257,197,545,170,162,18465,419,107,931,1140,438,15626,72,104,219,336,217,1527,278,122,252,56,62,62]
vbyp = []
for i in range(len(posts)):
    vbyp.append(views[i]/posts[i])
plt.plot(vbyp)
for i in range(len(vbyp)):
    plt.annotate(names[i],vbyp[i])
plt.show()

Without annotation I get an image like : enter image description here

But I want something like this :enter image description here

6
  • You need to use annotate correctly. Here is an example for you Commented Sep 18, 2018 at 17:09
  • To position an element on a plane you need two coordinates, usually called x and y. You need to supply those two coordinates as a tuple or list to the annotate's xy argument. Here you only supply a single number. Commented Sep 18, 2018 at 17:09
  • Also, could you tell us where exactly are to trying to put the names? Do you want them as x-tick labels on the x-axis? I think what you want is plt.annotate(names[i],(i, vbyp[i])) Commented Sep 18, 2018 at 17:13
  • Thanks for the help :) Commented Sep 18, 2018 at 17:18
  • @KartikeySingh: Glad to help. You are welcome Commented Sep 18, 2018 at 17:19

1 Answer 1

1

There are two possibilities to relate your names with the corresponding values. You will have to choose for your own whichever you like the best.

First: using your method correctly which gives not so good plot. In annotate, you have to specify your string names[i] and an (x,y) coordinate for which you were just providing a single number so far.

fig = plt.figure(figsize=(9,5))    

# Your code here
for i in range(len(vbyp)):
    plt.annotate(names[i],(i, vbyp[i]))

Output

enter image description here

Second : Using names as x-tick labels which generates much better and readable plot.

plt.xticks(range(25), names, rotation=45)

Output

enter image description here

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

Comments

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.