I am trying to understand graphing using Python. I want to understand what do "x_values" do in the following code and how does it work. I tried to change the numbers to see what it does affect to, but it gave me "shape dismatch" error saying "objects cannot be broadcast to a single shape".
Also, I want to know how I can use the square bars in the graph, name each one of them, but also still keep numbering on axises.
Ant help is appreciated!
Form I drove the code/graphs from: Placing text values on axis instead of numeric values
Thanks.
I am not sure where it goes wrong, that's why I did not know what I should change.
import matplotlib.pyplot as plt
import numpy as np
y_values = [0.1, 0.3, 0.4, 0.2]
text_values = ["word 1", "word 2", "word 3", "word 4"]
x_values = np.arange(1, len(text_values) + 1, 1)
plt.bar(x_values, y_values, align='center')
# Decide which ticks to replace.
new_ticks = ["word for " + str(y) if y != 0 else str(y) for y in y_values]
plt.yticks(y_values, new_ticks)
plt.xticks(x_values, text_values)
plt.show()
I expect the squares' names to show up on the axis as well as numbering on the x-y axises at the same time (showing the square on the axis with its name under it, and have the numbering still on the axis)
In your code, text_values
is a list which has 4 strings in it. So it has 4 elements and the length of this list is 4. This is obtained using the command len(text_values)
. So now the following command
np.arange(1, len(text_values) + 1, 1)
becomes
np.arange(1, 4 + 1, 1)
which means
np.arange(1, 5, 1)
This will generate consecutive numbers starting from 1 (the first value) up to the second value minus 1 (5 - 1 = 4) in steps of 1 (the third value). So you will get
x_values = [1, 2, 3, 4]
Now you use these values as the x-argument for the bar chart. So your bars will be positioned at x = 1, x = 2, x = 3, x= 4. This is what you see in your figure.