直接抄官网import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
labels = ['小米', '荣耀', '华为']
taobao = [9, 20, 5]
jingdong = [8, 30, 4]
x = [1, 2, 3]
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar([i - width / 2 for i in x], taobao, width, label='淘宝')
rects2 = ax.bar([i + width / 2 for i in x], jingdong, width, label='京东')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('销量')
ax.set_title('销量对比')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
fig.tight_layout()
plt.show()
|