Question 5 "Only length -1 arrays can be converted to Python scalars while plot showing
Hello, I'm getting an error for question 5 and I don't understand how to prevent it. My code is as follows:
"import string
string.ascii_lowercase
from random import shuffle
x = [[i] for i in range(26)]
shuffle(x)
letters = list(string.ascii_lowercase)
numbers = x
solution = dict(zip(letters,numbers))
import matplotlib.pyplot as plt
letters,numbers = zip(*solution.items())
print(letters)
print(numbers)
plt.bar(letters,numbers)
plt.show()"
Thanks!
Hey,
Thank you for your question and your solution to the exercise!
The documentation of matplotlib's bar()
method instructs that both the first and the second argument the method takes in have to be either float or array-like objects. Typing
type(letters)
type(numbers)
in your code, you will see that those variables are, in fact, tuples. We therefore need to convert them to array-like objects in order to use the bar()
method. The following piece of code could do that:
import numpy as np
letters = np.asarray(letters)
numbers = np.asarray(numbers).reshape(1, 26)[0]
plt.bar(letters,numbers)
plt.show()
Here, I redefine the letters
and numbers
variables such that they are both ndarray
objects containing 26 elements.
Hope this helps!
Kind regards,
365 Hristina