matplotlib做分组柱状图

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值