Matplotlib 使用模板

Matplotlib 使用模板

整理 Matplot 的画图使用方法,需要画图时,只需要修改 X、Y 的值,Matplot 画图部分的代码可以注释掉不想要的功能,以及适当修改部分功能。(持续更新中)

1 直角坐标图

以下使用 Numpy 库实现双立方缩放算法公式,并且使用 Matplot 展示双立方缩放函数的形状。双立方缩放公式如下:

在这里插入图片描述

python程序如下:

import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt

##########################################################################
# Bicubic Function
##########################################################################
def u(x, a):
  if (abs(x) >= 0) & (abs(x) <= 1):
    u = (a+2)*(abs(x)**3)-(a+3)*(abs(x)**2)+1
  elif (abs(x) > 1) & (abs(x) <= 2):
    u = a*(abs(x)**3)-(5*a)*(abs(x)**2)+(8*a)*abs(x)-4*a
  else:
    u = 0.0
  return u

# X 变量,定义80个
X  = np.linspace(-2, 2, 80, endpoint=True)
# Y 变量,定义80个
Y1 = np.linspace(-1, 1, 80, endpoint=True)
Y2 = np.linspace(-1, 1, 80, endpoint=True)
Y3 = np.linspace(-1, 1, 80, endpoint=True)
Y4 = np.linspace(-1, 1, 80, endpoint=True)

# 计算双立方值
for i in range(X.size):
  Y1[i] = u(X[i], -0.5)
  Y2[i] = u(X[i], -0.25)
  Y3[i] = u(X[i], 0.25)
  Y4[i] = u(X[i], 0.5)

##########################################################################
# Define Matplot
##########################################################################
###### 定义子图
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10,6))

###### 设置绘图属性
axes[0,0].set(xlim=[-2, 2], ylim=[-0.1, 1.0], title='BiBubic a=-0.5', 
              ylabel='U Value', xlabel='X Value')
axes[0,1].set(xlim=[-2, 2], ylim=[-0.1, 1.0], title='BiBubic a=-0.25', 
              ylabel='U Value', xlabel='X Value')
axes[1,0].set(xlim=[-2, 2], ylim=[-0.1, 1.0], title='BiBubic a=0.25', 
              ylabel='U Value', xlabel='X Value')
axes[1,1].set(xlim=[-2, 2], ylim=[-0.1, 1.0], title='BiBubic a=0.5', 
              ylabel='U Value', xlabel='X Value')
###### 连续线条
axes[0,0].plot(X, Y1, color="lightblue", linewidth=1, marker='none', linestyle='dashed', label='f(x)')
axes[0,1].plot(X, Y2, color="lightblue", linewidth=1)
axes[1,0].plot(X, Y3, color="lightblue", linewidth=1)
axes[1,1].plot(X, Y4, color="lightblue", linewidth=1)

# 在x=-0.5的位置加上注释
alph = np.linspace(-0.5, -0.5, 11, endpoint=True)
axes[0,0].plot(alph, Y1[20:31], color='red', linewidth=0.5, linestyle='dashed')
axes[0,0].scatter(alph[0], Y1[30], 20, color='red')
axes[0,0].annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', # 该公式可自行修改
         xy=(alph[10], Y1[30]), xycoords='data',
         xytext=(-90, +20), textcoords='offset points', fontsize=12,
         arrowprops=dict(arrowstyle="-|>", connectionstyle="arc3,rad=0.3"))

###### 布局 数值都是百分比
# hspace,wspace:水平、垂直间隔
# left,right,top,bottom:边距
fig.subplots_adjust(wspace=0.5, hspace=0.5, left=0.1, right=0.9, top=0.9, bottom=0.1)

###### 显示标签
axes[0,0].legend(loc='upper right')

###### 调整坐标轴
# 把上、右边框设置为无色再调整
axes[0,0].spines['right'].set_color('none')
axes[0,0].spines['top'].set_color('none')
# 移动坐标轴,将bottom即x坐标轴移动到y=0的位置
axes[0,0].xaxis.set_ticks_position('bottom') # 选定x轴
axes[0,0].spines['bottom'].set_position(('data', 0))
# 将left 即y坐标轴设置到x=0的位置
axes[0,0].yaxis.set_ticks_position('left') # 选定y轴
axes[0,0].spines['left'].set_position(('data', 0))

###### 绘图风格
# print(plt.style.available)
# plt.style.use('dark_background')
# plt.style.use('seaborn-colorblind')

###### 保存图片
# fig.savefig('./matplot_figure.png', dpi=128)

plt.show()

运行结果如下:

在这里插入图片描述

2 散点图

python 程序如下:

import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt

##########################################################################
# 定义 X Y 值
##########################################################################
# X 变量
X1 = np.random.randint(-10, 10, 20)
X1 = np.random.randint(-10, 10, 20)
X2 = np.random.randint(-10, 10, 20)
X3 = np.random.randint(-10, 10, 20)
X4 = np.random.randint(-10, 10, 20)
# Y 变量
Y1 = np.random.randint(-10, 10, 20)
Y2 = np.random.randint(-10, 10, 20)
Y3 = np.random.randint(-10, 10, 20)
Y4 = np.random.randint(-10, 10, 20)


##########################################################################
# Define Matplot
##########################################################################
###### 定义子图
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10,6))

###### 设置绘图属性
axes[0,0].set(xlim=[-10, 10], ylim=[-10, 10], title='Scatter1', 
              ylabel='Y Value', xlabel='X Value')
axes[0,1].set(xlim=[-10, 10], ylim=[-10, 10], title='Scatter2', 
              ylabel='Y Value', xlabel='X Value')
axes[1,0].set(xlim=[-10, 10], ylim=[-10, 10], title='Scatter3', 
              ylabel='Y Value', xlabel='X Value')
axes[1,1].set(xlim=[-10, 10], ylim=[-10, 10], title='Scatter4', 
              ylabel='Y Value', xlabel='X Value')
###### 绘制散点
axes[0,0].scatter(X1, Y1, color='r', marker='h', label='Scatter1')
axes[0,1].scatter(X2, Y2, color='b', marker='<', label='Scatter2')
axes[1,0].scatter(X3, Y3, color='g', marker='o', label='Scatter3')
axes[1,1].scatter(X4, Y4, color='#ffd700', marker='p', label='Scatter4')

###### 布局 数值都是百分比
# hspace,wspace:水平、垂直间隔
# left,right,top,bottom:边距
fig.subplots_adjust(wspace=0.5, hspace=0.5, left=0.1, right=0.9, top=0.9, bottom=0.1)

###### 显示标签
axes[0,0].legend(loc='upper right')
axes[0,1].legend(loc='upper right')
axes[1,0].legend(loc='upper right')
axes[1,1].legend(loc='upper right')

###### 调整坐标轴(axes[0,0])
# 把上、右边框设置为无色再调整
axes[0,0].spines['right'].set_color('none')
axes[0,0].spines['top'].set_color('none')
# 移动坐标轴,将bottom即x坐标轴移动到y=0的位置
axes[0,0].xaxis.set_ticks_position('bottom') # 选定x轴
axes[0,0].spines['bottom'].set_position(('data', 0))
# 将left 即y坐标轴设置到x=0的位置
axes[0,0].yaxis.set_ticks_position('left') # 选定y轴
axes[0,0].spines['left'].set_position(('data', 0))

###### 绘图风格
# print(plt.style.available)
# plt.style.use('dark_background')
# plt.style.use('seaborn-colorblind')

###### 保存图片
# fig.savefig('./matplot_figure.png', dpi=128)

plt.show()

效果如下:
在这里插入图片描述

3 直方图

python 程序如下:

import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt

##########################################################################
# 定义直方图数据
##########################################################################
# 随机数据 randint=[0, 100)
data1 = np.random.randint(0, 100, 20)
data2 = np.random.randint(0, 100, 20)
# data1 = np.random.randint(50, 100, 20) # 堆叠显示
# data2 = np.random.randint(0, 50, 20) # 堆叠显示
X1 = range(len(data1))
X2 = range(len(data2))
# x轴刻度
label_list = np.arange(2000, 2020, 1)# 横坐标刻度显示值(20个)
# label_list = ['2014', '2015', '2016', '2017']

##########################################################################
# Define Matplot
##########################################################################
###### 定义子图
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10,6))

# 设置matplotlib正常显示中文和负号
mpl.rcParams['font.sans-serif']=['SimHei']   # 用黑体显示中文
mpl.rcParams['axes.unicode_minus']=False     # 正常显示负号

###### 设置绘图属性
axes.set(title='CppCompany1', ylabel='value', xlabel='Yera')

###### 柱状图(bar垂直柱状图,barh水平柱状图)
# 绘制柱状体,x偏移值,height高度,width宽度%,alpha透明度%
rects1 = axes.bar(x=X1, align="center", height=data1, width=0.4, alpha=0.4, color='red', label='部门一')
rects2 = axes.bar(x=[i+0.4 for i in X2], align="center", height=data2, width=0.4, alpha=0.4, color='blue', label='部门二')
# rects1 = axes.bar(x=X1, align="center", height=data1, width=0.4, alpha=0.4, color='#960000', label='部门一') # 堆叠显示
# rects2 = axes.bar(x=X1, align="center", height=data2, width=0.4, alpha=1, color='#009600', label='部门二') # 堆叠显示

# 柱状体上方的数值
for rect in rects1:
    height = rect.get_height()
    plt.text(rect.get_x() + rect.get_width() / 2, height + 1, str(height), ha='center', va='bottom')
for rect in rects2:
    height = rect.get_height()
    plt.text(rect.get_x() + rect.get_width() / 2, height + 1, str(height), ha='center', va='bottom')

# X轴数值,0.2%为偏移数值
plt.xticks([index+0.2 for index in X1], label_list)
# plt.xticks(X1, label_list) # 堆叠显示
# Y轴数值
# plt.yticks()

###### 显示标签 loc=['lower left', 'upper right', 'upper left', 'lower right']
axes.legend(loc='upper right')

###### 绘图风格
# print(plt.style.available)
# plt.style.use('dark_background')
# plt.style.use('seaborn-colorblind')

###### 保存图片
# fig.savefig('./matplot_figure.png', dpi=128)

plt.show()

效果如下1:

在这里插入图片描述

效果如下2:(堆叠显示)

在这里插入图片描述

4 雷达图

python 程序如下:(参考:https://blog.csdn.net/qq_30992103/article/details/101905466)

import matplotlib.pyplot as plt
import numpy as np

p1={"编程能力":60,"沟通技能":70,"专业知识":65,"团体协作":75,"工具掌握":80} #创建第一个人的数据
p2={"编程能力":70,"沟通技能":60,"专业知识":75,"团体协作":65,"工具掌握":70} #创建第二个人的数据

# 分别提取两个人的信息和对应的标签
data1=np.array([i for i in p1.values()]).astype(int) #提取第一个人的信息
data2=np.array([i for i in p2.values()]).astype(int) #提取第二个人的信息
label=np.array([j for j in p1.keys()]) #提取标签

angle = np.linspace(0, 2*np.pi, len(data1), endpoint=False) #data里有几个数据,就把整圆360°分成几份
# 闭合的目的是在绘图时能够生成闭合的环
angles = np.concatenate((angle, [angle[0]])) #增加第一个angle到所有angle里,以实现闭合
data1 = np.concatenate((data1, [data1[0]])) #增加第一个人的第一个data到第一个人所有的data里,以实现闭合
data2 = np.concatenate((data2, [data2[0]])) #增加第二个人的第一个data到第二个人所有的data里,以实现闭合

fig = plt.figure()
ax = fig.add_subplot(111, polar=True)  # 设置坐标轴为极坐标
# 绘制两个数据样本的闭合环
ax.plot(angles, data1, 'bo-', linewidth=2, color='green', alpha=0.5)
ax.fill(angles, data1, facecolor='red', alpha=0.2)
ax.plot(angles, data2, 'bo-', linewidth=2, color='blue', alpha=0.5)  # 
ax.fill(angles, data2, facecolor='steelblue', alpha=0.5)
# 设置圆周每一维上显示的样本
ax.set_thetagrids(angle * 180/np.pi, label, fontproperties='SimHei', color='gray', fontsize=13)
# 设置在半径方向上要显示的文本和显示文本的角度
ax.set_rgrids(np.arange(0, 81, 20),angle=45)
ax.set_rlim(0, 100)
ax.set_title('matplotlib 雷达图', va='bottom', fontproperties='SimHei', color='gold', fontsize=15)
# help(ax.set_thetagrids)

plt.show()

5 饼图

Python 程序如下:(参考:https://blog.csdn.net/qq_30992103/article/details/101905466)

import matplotlib.pyplot as plt
import matplotlib

matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False

label_list = ["第一部分", "第二部分", "第三部分"]    # 各部分标签
size = [55, 35, 10]    # 各部分大小
color = ["#ffcccc", "#ffff99", "#0066cc"]     # 各部分颜色
explode = [0.05, 0.05, 0.05]   # 各部分突出值
"""
绘制饼图
explode:设置各部分突出
label:设置各部分标签,
labeldistance:设置标签文本距圆心位置,1.1表示1.1倍半径
autopct:设置圆里面文本
shadow:设置是否有阴影
startangle:起始角度,默认从0开始逆时针转
pctdistance:设置圆内文本距圆心距离
返回值
l_text:圆内部文本,matplotlib.text.Text object
p_text:圆外部文本
"""
patches, l_text, p_text = plt.pie(size, explode=explode, colors=color, labels=label_list, 
                                  labeldistance=1.1, autopct="%1.1f%%", shadow=True, startangle=90, pctdistance=0.6)
plt.axis("equal")    # 设置横轴和纵轴大小相等,这样饼才是圆的
plt.legend()
plt.show()

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值