我创建了一个Python函数(见下面的代码),当调用它时,它会绘制一个工作正常的分组条形图。我还附上了创建的图表的图像。
我对此代码有疑问。
1,2,3,4,5,6,7,8,9,10
,为 data_list
内的每个索引列表打印 6 次。然后将 10 个分组的条形图彼此分开,以便更明显且更易于解释?我在 Python 上绘制图表方面没有太多经验,因此希望得到一些帮助:)
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")
在回答您的问题之前,请注意以下几点:确保您的缩进正确;考虑对数组使用 numpy(如果你知道自己在做什么,会更快更容易);不要使用 list 作为变量名,因为它在 Python 中有特定用途。另外,如果您想要第 1 点的更完整答案,请参阅第 3 点答案。
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])
categories = ['example1', 'example2',...'example6']
plt.legend(categories, title='Legend')
希望这有帮助。