6

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

2 Answers 2

6
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)
Sign up to request clarification or add additional context in comments.

6 Comments

got this error: in <module> ax.bar(x,y) TypeError: unsupported operand type(s) for +: 'int' and 'str'
The code works on my computer. I edited it. Please try again.
yes it works. i forgot that my y list was in string format as well. Had to transform it to integer. Thank you :)
@Moritz You shouldn't add questions in answers. If you have a question, add a question ;)
yeah, you are right. Should I delete the question ?
|
2

Just add two lines:

import matplotlib.pyplot as plt
y = [1, 2, 3, 4, 5]
x_name = ['apple', 'orange', 'pear', 'mango', 'peach']
x = np.arange(len(x_name))  # <--
plt.bar(x, y)
plt.xticks(x, x_name)  # <--
plt.show()

enter image description here

Plot plt.bar(x_name, y) directly will be supported in v2.1, see here https://github.com/matplotlib/matplotlib/issues/8959

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.