import matplotlib.pyplot as plt
import numpy as np
species = ("Adelie", "Chinstrap", "Gentoo")
penguin_means = {'Bill Depth':(18.35,18.43,14.98),
'Bill Length':(38.79,48.83,47.5),
'Flipper Length':{189.95,195.82,217.19}}
x = np.arange(len(species)) # [0 1 2]
width = 0.15 # 柱子的宽度
multiplier = 0 # 乘数
# fig代表绘图窗口(Figure);ax代表这个绘图窗口上的坐标系(axis),一般会继续对ax进行操作。
fig,ax = plt.subplots(layout='constrained') # subplots 用于创建一个新的图形窗口或激活一个已存在的图形窗口,并返回一个或多个子图的坐标轴对象
for attribute,measurement in penguin_means.items(): # 字典的items() 方法,遍历字典,可以返回字典的键值对
offset = width*multiplier # 分组的间距
print(offset)
rects = ax.bar(x+offset,measurement,width,label=attribute)
ax.bar_label(rects,padding=3) #ax.bar_label 给bar添加标签
multiplier += 1
ax.set_ylabel('Length(mm)') # 设置y的标签
ax.set_title('Penguin attributes by species') # 设置标题
ax.set_xticks(x + width,species) # 设置X轴标签
# ax.legend(loc='upper left',ncols=3)
ax.legend(loc='upper left') # 设置图例的位置
ax.set_ylim(0,250) # 设置y轴的取值范围
plt.show()
02-04
3707
07-30
3525
10-28
4190