import matplotlib.pyplot as plt import numpy as np #数据 species = ['Adelie','Chinstrap','Gentoo'] attributes = ['Bill Depth','Bill Length','Flipper Length'] data = [[18.35,18.43,14.98],[38.79,48.83,47.5],[189.95,195.82,217.19]] fig,ax = plt.subplots() bar_width = 0.25 bar_positions = np.arange(len(species)) bar_positions_Adelie = bar_positions-bar_width bar_positions_Chinstrap = bar_positions bar_positions_Gentoo = bar_positions+bar_width #绘制Adelie的柱状图 ax.bar(bar_positions_Adelie,data[0],width=bar_width,label=attributes[0]) #绘制Chinstrap的柱状图 ax.bar(bar_positions_Chinstrap,data[1],width=bar_width,label=attributes[1]) #绘制Gentoo的柱状图 ax.bar(bar_positions_Gentoo,data[2],width=bar_width,label=attributes[2]) #设置图形属性 ax.set_ylabel('Length(mm)') ax.set_title('Penguin attributes by species') ax.set_xticks(np.arange(len(species))) ax.set_xticklabels(species) ax.legend() for i in range(len(attributes)): for j in range(len(species)): labe = str(data[j][i]) ax.annotate(label,xy=(bar_positions[j]+(i-1)*bar_width/2,data[j][i]),ha='center',va='bottom') plt.show()优化代码
时间: 2023-12-06 19:42:45 浏览: 339
import numpy as np import matplotlib.pyplot as plt import math
import matplotlib.pyplot as plt
import numpy as np
# 数据
species = ['Adelie','Chinstrap','Gentoo']
attributes = ['Bill Depth','Bill Length','Flipper Length']
data = np.array([[18.35,18.43,14.98],[38.79,48.83,47.5],[189.95,195.82,217.19]])
# 设置柱状图参数
bar_width = 0.25
bar_positions = np.arange(len(species))
bar_positions_Adelie = bar_positions-bar_width
bar_positions_Chinstrap = bar_positions
bar_positions_Gentoo = bar_positions+bar_width
# 绘制柱状图
fig,ax = plt.subplots()
for i in range(len(attributes)):
ax.bar(bar_positions_Adelie+i*bar_width, data[:,i], width=bar_width, label=attributes[i])
# 设置图形属性
ax.set_ylabel('Length(mm)')
ax.set_title('Penguin attributes by species')
ax.set_xticks(np.arange(len(species)))
ax.set_xticklabels(species)
ax.legend()
# 添加数值标签
for i in range(len(attributes)):
for j in range(len(species)):
label = str(data[j][i])
ax.annotate(label, xy=(bar_positions[j]+i*bar_width-0.05, data[j][i]+2), fontsize=8)
plt.show()
阅读全文