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:
from random import shuffle
x = [[i] for i in range(26)]
letters = list(string.ascii_lowercase)
numbers = x
solution = dict(zip(letters,numbers))
import matplotlib.pyplot as plt
letters,numbers = zip(*solution.items())
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
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) plt.bar(letters,numbers) plt.show()
Here, I redefine the
numbers variables such that they are both
ndarray objects containing 26 elements.
Hope this helps!