gpt4 book ai didi

具有多个 x 标签的 Python 分组条形图

转载 作者:行者123 更新时间:2023-12-05 03:25:22 24 4
gpt4 key购买 nike

我想绘制一个相对简单的条形图,但很难使用 Matplotlib 进行绘制。我能得到一些帮助吗?我想准备一个如图所示的图表 Bar Chart .下面显示了测试 1、2 和 3 的样本数据。

我有 20 多个测试结果,我想绘制在一个大的单图上,所以如果可能的话,我更愿意循环浏览彩色 map 。

到目前为止,我的工作代码是这样的。如你所见my attempt远不是我需要的。

"""
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()

enter image description here

关于具有多个 x 标签的 Python 分组条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72014867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com