从python中的元素列表绘制直方图

时间:2019-04-09 10:29:22

标签: python list bar-chart histogram

我有两个列表,它本身就是列表。我想使用这些列表绘制直方图。

以下是列表:

param_main_list

[['Para_length', 'Question1', 'Answer1', 'Question2', 'Answer2'], 
['Para_length', 'Question1', 'Answer1', 'Question2', 'Answer2', 
'Question3', 'Answer3', 'Question4', 'Answer4', 'Question5', 'Answer5'], 
['Para_length', 'Question1', 'Answer1', 'Question2', 'Answer2', 
'Question3', 'Answer3', 'Question4', 'Answer4', 'Question5', 'Answer5'], 
['Para_length', 'Question1', 'Answer1', 'Question2', 'Answer2', 
'Question3', 'Answer3', 'Question4', 'Answer4', 'Question5', 'Answer5']]

main_list:

[1107, 64, 129, 64, 67]
[1223, 34, 129, 62, 244, 56, 136, 48, 128, 43, 180]
[1345, 47, 96, 63, 241, 79, 97, 82, 108, 62, 134]
[648, 35, 111, 78, 131, 56, 86, 28, 47, 64, 151]
[[1107, 64, 129, 64, 67], [1223, 34, 129, 62, 244, 56, 136, 48, 128, 43, 
180], [1345, 47, 96, 63, 241, 79, 97, 82, 108, 62, 134], [648, 35, 111, 
78, 131, 56, 86, 28, 47, 64, 151]]

考虑这些直方图从列表中一对一对应,即 param_main_list 的第一个元素和 main_list

的第一个元素

我能够打印一个直方图,但是我想分别为每种情况打印多个直方图。我生成的是下面的

enter image description here

上面的代码是:

for index in range(0,len(main_list)):     
    xpos = np.arange(len(main_list[index]))   
    plt.xticks(xpos,param_main_list[index])
    plt.bar(param_main_list[index],main_list[index])
    plt.hist() 

这不是重复的,我已经检查了所有解决方案,请为此提供帮助。

1 个答案:

答案 0 :(得分:0)

遍历subplot的轴

%matplotlib inline
import matplotlib.pyplot as plt
x=[['Para_length', 'Question1', 'Answer1', 'Question2', 'Answer2'], 
['Para_length', 'Question1', 'Answer1', 'Question2', 'Answer2','Question3', 'Answer3', 'Question4', 'Answer4', 'Question5', 'Answer5'], 
['Para_length', 'Question1', 'Answer1', 'Question2', 'Answer2','Question3', 'Answer3', 'Question4', 'Answer4', 'Question5', 'Answer5'], 
['Para_length', 'Question1', 'Answer1', 'Question2', 'Answer2','Question3', 'Answer3', 'Question4', 'Answer4', 'Question5', 'Answer5']]  

y=[[1107, 64, 129, 64, 67], 
[1223, 34, 129, 62, 244, 56, 136, 48, 128, 43, 180], 
[1345, 47, 96, 63, 241, 79, 97, 82, 108, 62, 134], 
[648, 35, 111, 78, 131, 56, 86, 28, 47, 64, 151]]


fig, axs = plt.subplots(1,4)

for i,ax in enumerate(axs):
    ax.bar(x[i],y[i])
    ax.set_xticklabels(x[i], rotation=90)


plt.show()