Python画柱状图(双柱状图,三柱状图)且显示对应数值

时间:2025-02-18 10:09:24
  • import matplotlib
  • import as plt
  • import numpy as np
  • from pylab import mpl
  • ['-serif']=['KaiTi']
  • ['']=['KaiTi']
  • labels = ['A', 'B', 'C', 'D']
  • a = [0.78, 0.89, 0.90, 0.65]
  • b = [0.25, 0.80, 0.59, 0.60]
  • c = [0.81, 0.50, 0.36, 0.39]
  • x = (len(labels)) # the label locations
  • width = 0.22 # the width of the bars
  • fig, ax = (figsize=(5,4))
  • rects1 = (x - width,a, width, label='数据一',alpha=1)
  • rects2 = (x , b, width, label='数据二',alpha=1)
  • rects3 = (x + width, c, width, label='数据三',alpha=1)
  • # Add some text for labels, title and custom x-axis tick labels, etc.
  • ax.set_ylabel('Y轴标签',fontsize=10)
  • ax.set_xlabel('X轴标签',fontsize=10)
  • ax.set_yticks([0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1])
  • ax.set_xticks(x)
  • ax.tick_params(direction='in')
  • ax.set_xticklabels(labels)
  • ()
  • def autolabel(rects):
  • """Attach a text label above each bar in *rects*, displaying its height."""
  • for rect in rects:
  • height = rect.get_height()
  • ('{}'.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)
  • autolabel(rects3)
  • [''] = 'in' # in; out; inout
  • [''] = 'in'
  • fig.tight_layout()
  • ()