Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot a bar chart using matplotlib - type error

I am trying to plot a frequency distribution (of occurences of words and their frequency)

This is my code:

import matplotlib.pyplot as plt

y = [1,2,3,4,5]
x = ['apple', 'orange', 'pear', 'mango', 'peach']

plt.bar(x,y)
plt.show

However, i am getting this error:

TypeError: cannot concatenate 'str' and 'float' objects
like image 851
jxn Avatar asked Jun 25 '15 17:06

jxn


1 Answers

import matplotlib.pyplot as plt
import numpy as np
y = [1,2,3,4,5]
x = np.arange(0,len(y)) + 0.75
xl = ['', 'apple', 'orange', 'pear', 'mango', 'peach']

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x,y,0.5)
ax.set_xticklabels(xl)
ax.set_xlim(0,5.5)

It would be interesting if there is a better method for setting the labels to be in the middle of the bars.

According to this SO post, there is a better solution:

import matplotlib.pyplot as plt
import numpy as np
y = [1,2,3,4,5]
# adding 0.75 did the trick but only if I add a blank position to `xl`
x = np.arange(len(y))
xl = ['apple', 'orange', 'pear', 'mango', 'peach']

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x,y,0.5, align='center')
ax.set_xticks(x)
ax.set_xticklabels(xl)
like image 60
Moritz Avatar answered Oct 27 '22 00:10

Moritz