Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting this matplotlib error for plotting a categorical variable?

I feel stupid but I cannot seem to fix this error or find any solution online. Why do I keep getting the following error no matter how I try to plot it using matplotlib?

For instance even the following code gives me the same error -

names = list(fig1['day'])
values = list(fig1['count'])
fig, axs = plt.subplots(figsize=(25, 10))
axs.bar(names, values, color='plum')

matplotlib.category: Using categorical units to plot a list of strings that are all parsable as floats or dates. If these strings should be plotted as numbers, cast to the appropriate data type before plotting.

enter image description here

UPDATE: I found the solution - https://discourse.matplotlib.org/t/why-am-i-getting-this-matplotlib-error-for-plotting-a-categorical-variable/21758/2

like image 485
Saayed Alam Avatar asked Aug 16 '26 04:08

Saayed Alam


1 Answers

Actually the right solution is this, because is more generic, applies not only to calendar objects:

fig, ax = plt.subplots()

names = ['Monday', 'Tuesday', 'Wednesday']
# you may try with: 
# names = ['1111', '2222', '3333']

# This variable is a range (numerical values) and we pass it for number of ticks on X axis:
rln = range(len(names))

values = [230, 112, 12]
ax.bar(rln, values)

# Finally, we are setting ticks labels on X axis:
plt.xticks(rln, names)
plt.show()
like image 186
Tomasz Mikolajczyk Avatar answered Aug 17 '26 18:08

Tomasz Mikolajczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!