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?
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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With