Issue
I have created a Python function (see below code) that when called, plots a grouped bar chart which is working ok. I have also attached an image of the created graph.
Is there a way instead of printing 1,2,3,4,5,6,7,8,9,10
on the x-axis, 6 times for each indexed list inside data_list
. And then separate each of the 10 grouped bars apart from each other so it is more obvious and easier to interpret?
import matplotlib.pyplot as plt
def plot_graph(list, title_str):
x_plot = []
y_plot = []
legend_labels = ['a', 'b', 'c', 'd', 'e', 'f']
x_labels = [1,2,3,4,5,6,7,8,9,10]
x_labels_text = ['red', 'blue', 'green', 'purple', 'olive', 'brown']
x_colors = ['tab:red', 'tab:blue', 'tab:green', 'tab:purple', 'tab:olive', 'tab:brown']
fig, ax = plt.subplots()
ax.set_xlabel('\nFault Type', fontsize=15)
ax.set_ylabel('Number of Errors (%)', fontsize=15)
ax.set_title('Total Number of Errors (%)', fontsize=15)
for i in range(len(list)):
for j in range(len(list[i])):
x_plot.append(x_labels[i])
y_plot.append(list[i][j])
ax.bar(range(len(x_plot)), y_plot, label=legend_labels, color=x_colors, width=0.5)
ax.set_xticks(range(len(x_plot)), x_plot)
ax.set_ylim(ymax=100)
#ax.legend(['a', 'b', 'c', 'd', 'e', 'f'])
patches, _ = ax.get_legend_handles_labels()
labels = [*'abcdef']
ax.legend(*patches, labels, loc='best')
fig.tight_layout()
plt.setp(ax.get_xticklabels(), fontsize=10)
plt.savefig("C:/CoolTermWin64Bit/CoolTermWin64Bit/uart_data/Gathered Data/Code Generated Data Files/" + title_str + ".pdf")
data_list = [ [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] ]
plot_graph(data_list, "data grouped bar graph")
Solution
Some notes before I answer your questions: Make sure your indentation is correct; consider using numpy for your arrays (faster and easier if you know what you're doing); don't use list as a variable name as it has a specific use in Python. Also, please see answer number 3 if you want a more complete answer for number 1.
- Not an exactly elegant solution, but it works:
for i in range(len(data)):
for j in range(len(data[i])):
if j == len(x_labels) // 2:
x_plot.append(i + 1)
else:
x_plot.append('')
y_plot.append(data[i][j])
- First of all, you need to fix your labels, there's something wrong with your code there. Here's how to add a legend:
categories = ['example1', 'example2',...'example6']
plt.legend(categories, title='Legend')
- Instead of writing out how to do a whole group bar chart (which is what you're looking for), I'm going to link a guide. This should help solve problem number 1 as well: https://matplotlib.org/stable/gallery/lines_bars_and_markers/barchart.html
Answered By - Max
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.