[英]Python Grouped bar chart with multiple x-labels
我想要 plot 一个相对简单的条形图,但是使用 Matplotlib 很难得到 plot。请问我能得到一些帮助吗? 我想准备一个图表,如Bar Chart所示。 下面显示了测试 1、2 和 3 的示例数据。
我有超过 20 个测试结果我想在大单 plot 上 plot 所以如果可能的话我更愿意循环浏览彩色地图。
到目前为止,我的工作代码是这样的。 如您所见,我的尝试远未达到我的需要。
"""
A B C
Test 1 1 1.5 2.5
Test 2 1.5 2 3.5
Test 3 1 0.5 1.5
"""
from matplotlib import pyplot as plt
import numpy as np
width = 0.2
x = np.arange(3)
#Test 1
val1 = [1, 1.5, 1]
lab1_x = ['A' for i in range(len(val1))]
plt.bar(x, val1, width)
plt.xticks(x, lab1_x)
#Test 2
val2 = [1.5,2,3.5]
lab2_x = ['B' for i in range(len(val2))]
plt.bar(x+width, val2, width)
plt.xticks(x, lab2_x)
#Test 3
val3 = [1,0.5,1.5]
lab3_x = ['C' for i in range(len(val3))]
plt.bar(x+ 2*width, val3, width)
plt.xticks(x, lab3_x)
plt.legend(["Test 1", "Test 2", "Test 3"], loc = 'best')
我设法得到了我需要的东西。 如果其他人有兴趣,请在这里分享。
from random import seed
from random import random
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import matplotlib as mpl
# name of colour map
cmap = mpl.cm.tab20c
totaltests = 10
# seed random number generator
seed(2)
A = []
# generate random numbers between 0-1
for _ in range(totaltests):
A.append(2*random())
# seed random number generator
seed(4)
B = []
# generate random numbers between 0-1
for _ in range(totaltests):
B.append(2*random())
# sum of two columns
sumbd = [x + y for x, y in zip(A, B)]
index = np.arange(len(sumbd))
bar_width = 0.3
shift = 0.5 # used to minimise gaps between each Test sets
ticklist = []
for i in ('A','B','C'):
for _ in range(totaltests):
ticklist.append(i)
#print(A)
ticklist = tuple(ticklist)
plt.xticks(np.append(np.append(index-shift , index-shift + bar_width/1), index-shift + 2*bar_width/1), # tick positions
ticklist, # label corresponding to each tick
rotation=0)
color_list = cmap([x for x in range(0,totaltests,1)])
Aplot = plt.bar(index-shift , A, bar_width-0.01, edgecolor ='black', color = color_list)
Bplot = plt.bar(index-shift + bar_width/1, B, bar_width-0.01, edgecolor ='black', color = color_list)
sumbedplot = plt.bar(index-shift +2* bar_width/1, sumbd, bar_width-0.01, edgecolor ='black', color = color_list)
handlesList = ['T'+str(x) for x in range(1,totaltests+1,1)]
# generate all handles for legend
for i in range(0,totaltests,1):
handlesList[i] = mpatches.Patch(color= color_list[i], label = "Test"+str(i+1))
# Rest of plotting
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Fig xxx')
plt.axis("tight")
plt.legend(handles=handlesList, bbox_to_anchor=(1.01, 1.0), loc='upper left')
plt.tight_layout()
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.