Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Bar string on x axis

I have 2 arrays like below:

x = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November',
 'December']
y = [5.3, 6.1, 25.5, 27.8, 31.2, 33.0, 33.0, 32.8, 28.4, 21.1, 17.5, 11.9]

and i need to put the months on x axis and max temperatures for months on y axis. However, when I use the code below:

    import matplotlib.pyplot as plt
import numpy as np

    x = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November',
         'December']
    y = [5.3, 6.1, 25.5, 27.8, 31.2, 33.0, 33.0, 32.8, 28.4, 21.1, 17.5, 11.9]

    plt.bar(x, y, color='green',align='center')
    plt.title('Max Temperature for Monthes')
    plt.legend()
    plt.show()

I get this value error: ValueError: could not convert string to float: 'January'

How can i solve this? How can i put string values on x axis?

like image 560
Habil Ganbarli Avatar asked Aug 26 '26 15:08

Habil Ganbarli


2 Answers

Matplotlib has an example that accomplishes what you're trying to do.

To create a plot, you have to have numerical data for both dimensions as otherwise, matplotlib doesn't know what to do. Instead, you have to add the strings as labels to your ticks:

import matplotlib.pyplot as plt
import numpy as np

x = range(12)
x_labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November',
     'December']
y = [5.3, 6.1, 25.5, 27.8, 31.2, 33.0, 33.0, 32.8, 28.4, 21.1, 17.5, 11.9]

plt.bar(x, y, color='green', align='center')
plt.title('Max Temperature for Monthes')
plt.xticks(x, x_labels, rotation='vertical')
plt.legend()
plt.show()
like image 97
finbarr Avatar answered Aug 29 '26 06:08

finbarr


You can use plt.xticks as documented here

Here's how to use it with your code:

import matplotlib.pyplot as plt
import numpy as np

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
monthsRange = np.arange(len(months))
temperatures = [5.3, 6.1, 25.5, 27.8, 31.2, 33.0, 33.0, 32.8, 28.4, 21.1, 17.5, 11.9]

plt.bar(monthsRange, temperatures, color='green')
plt.title('Max Temperature for Monthes')
plt.xticks(monthsRange, months)
plt.legend()
plt.show()
like image 34
sacha-cs Avatar answered Aug 29 '26 05:08

sacha-cs