文章目录
1、导入包
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
# 设置全局字体及大小,设置公式字体
config = {
"font.family":'serif', # 衬线字体
"font.size": 12, # 相当于小四大小
"mathtext.fontset":'stix', # matplotlib渲染数学字体时使用的字体,和Times New Roman差别不大
"font.serif": ['SimSun'], # 宋体SimSun
"axes.unicode_minus": False, # 用来正常显示负号
"xtick.direction":'in', # 横坐标轴的刻度设置向内(in)或向外(out)
"ytick.direction":'in', # 纵坐标轴的刻度设置向内(in)或向外(out)
}
rcParams.update(config)
%matplotlib inline
# 内置魔法函数,不用再 plt.show()
2、一列柱状图
#定义函数来显示柱子上的数值
def autolabel(rects):
for rect in rects:
height = rect.get_height()
plt.text(rect.get_x()+rect.get_width()/2.-0.08, 1.03*height, '%s' % int(height), size=10, family="Times new roman")
plt.figure(figsize=(4,3))
x = ["A", "B", "C", "D"]
y = [ 65, 70, 75, 80]
cm = plt.bar(x, y, width=0.5, color=["blue", "green", "yellow", "magenta"])
autolabel(cm)
plt.ylim((0, 90))
plt.xlabel("类别", size=12)
plt.ylabel("数量", size=12)
plt.xticks(fontproperties='Times New Roman', size = 10)
plt.yticks(fontproperties='Times New Roman', size = 10)
plt.savefig(r'D:UsersAdministratorDesktop一列柱状图.png', dpi=600, bbox_inches='tight')
plt.show()
3、多列柱状图
labels = ["A", "B", "C", "D", "E"]
X = [ 60, 65, 70, 75, 80]
Y = [ 65, 70, 75, 80, 85]
Z = [ 70, 75, 80, 85, 90]
barWidth = 0.25 # 设置柱子的宽度
# 设置横轴刻度在多列柱子的中间
r1 = np.arange(len(X))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]
#定义函数来显示柱子上的数值
def autolabel(rects):
for rect in rects:
height = rect.get_height()
plt.text(rect.get_x()+rect.get_width()/2.-0.08, 1.02*height, '%s' % int(height), size=10, family="Times new roman")
plt.figure(figsize=(6,4))
cm = plt.bar(r1, X, color='cyan', width=barWidth, edgecolor='white', label='X')
autolabel(cm)
cm = plt.bar(r2, Y, color='yellow', width=barWidth, edgecolor='white', label='Y')
autolabel(cm)
cm = plt.bar(r3, Z, color='magenta', width=barWidth, edgecolor='white', label='Z')
autolabel(cm)
plt.ylim((0, 100))
plt.xlabel("类别", size=12)
plt.ylabel("数量", size=12)
plt.yticks(fontproperties='Times New Roman', size=10)
plt.xticks([r + barWidth for r in range(len(X))], labels=labels, fontproperties='Times New Roman', size=10)
plt.legend(prop={'family': 'Times New Roman', 'size': 10})
plt.savefig(r'D:UsersAdministratorDesktop多列柱状图.png', dpi=600, bbox_inches='tight')
plt.show()