Issue
I have to create a script to analyse some data that are lists of lists (format is shown below). I have also attached a quick drawing of the bar graph format that I want to use to visualise the data.
Basically, I want a bar graph that plots each of the 6 data points inside each of the 10 lists in y_data. And they should be labeled from a to f, respectively.
I have tried two nested for loops that append each list value to another x temp and y temp lists and plot each, but it doesn't seem to work.
How can I create this bar graph?
x_labels = ['a', 'b', 'c', 'd', 'e', 'f']
y_data = [ [ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ] ]
Here is one of my code attempts so far:
(The list of lists of lists is causing my confusion here!)
import matplotlib.pyplot as plt
x_labels = ['a', 'b', 'c', 'd', 'e', 'f']
y_data = [ [ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ],
[ [10], [20], [30], [40], [50], [60] ] ]
x_temp = []
y_temp = []
fig, ax = plt.subplots()
for i in range(len(y_data)):
for j in range(len(y_data[i])):
x_temp.append(x_labels[j])
y_temp.append(y_data[i][j])
ax.bar(x_temp, y_temp)
plt.show()
Solution
IIUC, you want multiple sections of the same barplot that share the same x-axis labels.
Before this can be done, we have to make one small change to how you're creating y_temp
(by the way, that's not a good variable name). Because y_data
is structured as it is (I'm not sure why it is that way), you have to also index the first value otherwise you end up with 1-element lists (print out y_temp
after the loop and you will see). So, the correction is:
y_temp.append(y_data[i][j][0])
Now, for the plotting, you will want to first map the bars to unique values and then change the tick labels. This can be done by using range
for the x-values and then ax.set_ticks
to change them to the corresponding letters.
ax.bar(range(len(x_temp)), y_temp)
ax.set_xticks(range(len(x_temp)), x_temp)
fig.tight_layout()
fig.show()
So, in the end, only a couple of minor changes to your original code.
Answered By - jared
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.