Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib - could not convert string to float

I'm struggling to understand why matplotlib wants to convert a string to float for my x axis.

x values (month/day)

x = ['Jul 01', 'Jul 02', 'Jul 03', 'Jul 04', 'Jul 05', 'Jul 06', 'Jul 07', 'Jul 08', 'Jul 09', 'Jul 10', 'Jul 11', 'Jul 12', 'Jul 13', 'Jul 14', 'Jul 15', 'Jul 16', 'Jul 17', 'Jul 18', 'Jul 19', 'Jul 20', 'Jul 21', 'Jul 22', 'Jul 23', 'Jul 24', 'Jul 25', 'Jul 26', 'Jul 27', 'Jul 28', 'Jul 29', 'Jul 30', 'Jul 31', 'Aug 01', 'Aug 02', 'Aug 03', 'Aug 04', 'Aug 05', 'Aug 06', 'Aug 07', 'Aug 08', 'Aug 09', 'Aug 10', 'Aug 11', 'Aug 12', 'Aug 13', 'Aug 14', 'Aug 15', 'Aug 16', 'Aug 17', 'Aug 18', 'Aug 19', 'Aug 20', 'Aug 21', 'Aug 22', 'Aug 23', 'Aug 24', 'Aug 25', 'Aug 26', 'Aug 27', 'Aug 28', 'Aug 29', 'Aug 30', 'Aug 31', 'Sep 01', 'Sep 02', 'Sep 03', 'Sep 04', 'Sep 05', 'Sep 06', 'Sep 07', 'Sep 08', 'Sep 09', 'Sep 10', 'Sep 11', 'Sep 12', 'Sep 13', 'Sep 14', 'Sep 15', 'Sep 16', 'Sep 17', 'Sep 18', 'Sep 19', 'Sep 20', 'Sep 21', 'Sep 22', 'Sep 23', 'Sep 24', 'Sep 25', 'Sep 26', 'Sep 27', 'Sep 28', 'Sep 29', 'Sep 30']

y values (avg temp)

y = [80.5, 81.5, 78.0, 69.5, 72.0, 75.0, 81.0, 81.0, 79.5, 77.5, 78.5, 78.0, 77.5, 78.0, 79.0, 74.5, 74.0, 72.5, 72.0, 73.0, 76.0, 78.5, 80.0, 75.0, 74.0, 75.0, 78.0, 75.0, 70.0, 71.5, 75.0, 77.5, 68.5, 71.0, 77.0, 80.5, 76.5, 74.5, 74.0, 76.5, 78.0, 79.0, 74.5, 75.0, 70.0, 67.0, 70.5, 74.0, 72.0, 73.0, 77.0, 74.0, 72.0, 72.0, 72.0, 76.0, 79.5, 80.0, 74.0, 70.5, 72.5, 81.5, 81.5, 84.5, 79.0, 78.0, 79.5, 79.0, 73.0, 70.0, 68.0, 71.5, 76.0, 70.0, 63.5, 62.0, 63.0, 64.0, 64.0, 66.5, 60.0, 66.0, 71.0, 63.0, 61.5, 64.5, 60.5, 67.5, 71.5, 74.0, 73.0, 66.5]

Let's say I do an extremely simply plot

plt.plot(x,y)

I get the error: ValueError: could not convert string to float 'Jul 01'.

This data is extracted out of a dataframe. If I try plotting using the dataframe, I am able to successfully create the plot. However, I want to overlay multiple datasets on one plot - so I'd like to be able to do multiple plt.plot calls using different datasets.

cheers

like image 527
Gshock Avatar asked Sep 19 '17 15:09

Gshock


1 Answers

If you just want to plot with a list of strings in the x axis you could do:

xn = range(len(x))
plt.plot(xn, y)
plt.xticks(xn, x)

You first need to map your string labels to integers (x to xn), then use the second parameter or xticks to set it to the string values.

If you have multiple datasets you just have to loop the plt.plot line with diffetent y, and perform plt.xticks after it.

like image 70
Imanol Luengo Avatar answered Sep 28 '22 08:09

Imanol Luengo