-1
import matplotlib.pyplot as plt
x = ['Eric','Jhon','bill','Daniel']
y = [10, 17, 12.5, 20]
plt.plot(x,y)
plt.show()

When I run this code, I get this error ValueError: could not convert string to float:

I want all names in list x at x-axis and corresponding ages are in second list y which will be used in bar graph.

So here I have 1 more question Is it a good way to do in my case(I mean if we can create a list of tuples(name,age)) and that would be easy?? or something else.

user3628682
  • 685
  • 1
  • 11
  • 19
  • I'll answer your 2nd part here so it can be easily deleted after you've read it (as it's not part of the main question). You can either construct two arrays or have a list of tuples, it depends on what else you'll be doing with the data. Just bear in mind that you'll have to convert those tuples into two lists (`y` and `names`) when you want to do your plotting. **TL;DR - either way is fine.** – Ffisegydd Jun 02 '14 at 10:36

1 Answers1

2

The error occurs because matplotlib is expecting numerical data but you're providing strings (the names).

What you can do instead is plot your data using some numerical data and then replace the ticks on the x-axis using plt.xticks as below.

import matplotlib.pyplot as plt

names = ['Eric','John','Bill','Daniel']
x = range(len(names))
y = [10, 17, 12.5, 20]

plt.plot(x, y)

plt.xticks(x, names)

plt.show()

Plot example

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125