Matplotlib 绘图实用大全
创始人
2024-06-01 07:56:28
0

本文只介绍最简单基本的画图方法

预设

要想画出来的图有些逼格,首先应该进行如下设置

plt.rcParams['font.sans-serif']=['SimHei']    #画图时显示中文字体
plt.rcParams['axes.unicode_minus'] = False     #防止因修改成中文字符,导致某些 unicode 字符不能显示
plt.subplots_adjust(left=None, bottom=None, right=None, top=None,wspace=0.3)    #设置制子图之间的左右间距,left 等是设置画图区域与画布之间的间font1 = {'family' : 'SimHei',
'weight' : 'normal',
'size'   : 15,
}   #设置图例(legend)文字的格式的

绘制多幅图

基本格式:

fig = plt.figure(figsize=())
ax1 = plt.subplot(m,n,1)  #m 为行、n为列、1 为图序
plt.plot(xxxxx)ax2 = plt.subplot(m,n,2)
plt.plot(xxxx)......
示例如下:
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,2*np.pi,100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = x+1fig = plt.figure(figsize=(12,4))  #宽度、高度
ax1 = plt.subplot(1,3,1)
plt.plot(x,y1,linewidth=1.5,color='c',label=r'$y_1$',marker='o',markersize=4)
plt.xlabel('x',fontsize=24)
plt.ylabel(r'$y_1$',fontsize=24)
plt.ylim([-1,1])
plt.xlim([0,2*np.pi])
plt.legend(prop=font1,loc='best')
plt.grid()ax2 = plt.subplot(1,3,2)
plt.plot(x,y2,linewidth=3,color='r',label=r'$y_2$',linestyle='-.')
plt.xlabel('x',fontsize=24)
plt.ylabel(r'$y_2$',fontsize=24)
plt.ylim([-1,1])
plt.xlim([0,2*np.pi])
plt.legend(prop=font1,loc='best')
plt.grid()ax3 = plt.subplot(1,3,3)
plt.plot(x,y3,linewidth=1.5,color='b',label=r'$y_3$',linestyle='--')
plt.xlabel('x',fontsize=24)
plt.ylabel(r'$y_3$',fontsize=24)
plt.legend(prop=font1,loc='best')
plt.grid()

在这里插入图片描述
另外。plt.title 也可以设图片的标题,子图的标题也行

画骨骼图

先看效果:
在这里插入图片描述
这里要用 axe 来画图,而不能直接用 plt,代码如下:

def sigmoid(x):return 1./(1.+np.exp(-x))def relu(x):return np.where(x<0,0,x)def tanh(x):return 2*sigmoid(2*x)-1font1 = {'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 14,
}def plot_tran_fun():   plt.rcParams['font.sans-serif']=['SimHei']plt.rcParams['axes.unicode_minus'] = Falsefig = plt.figure(figsize=(8,6))ax1 = plt.subplot(2,2,1)x = np.arange(-10, 10)y = sigmoid(x)ax.spines['top'].set_color('none')ax.spines['right'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data',0))ax.set_xticks([-10,-5,0,5,10])ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data',0))ax.plot(x,y,label="Sigmoid",color = "blue")plt.legend(prop=font1,loc='lower right')
#    plt.show()
#
#    ax2 = plt.subplot(2,2,2)x = np.arange(-10, 10)y = tanh(x)ax.spines['top'].set_color('none')ax.spines['right'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data',0))ax.set_xticks([-10,-5,0,5,10])ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data',0))ax.plot(x,y,label="Tanh",color = "blue")plt.legend(prop=font1)
#    ax.show()   
#    ax = fig.add_subplot(223)
#     x = np.arange(-10, 10)y = relu(x)ax.spines['top'].set_color('none')ax.spines['right'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data',0))ax.set_xticks([-10,-5,0,5,10])ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data',0))ax.plot(x,y,label="ReLU",color = "blue")plt.legend(prop=font1)     
#    ax = fig.add_subplot(224)
#     x = np.arange(-10, 10)y = xax.spines['top'].set_color('none')ax.spines['right'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data',0))ax.set_xticks([-10,-5,0,5,10])ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data',0))ax.plot(x,y,label="Linear",color = "blue")plt.legend(prop=font1)plot_tran_fun()

其他画图

画出包围部分

一般用在画积分面积的时候,代码如下:

fig = plt.figure(figsize=(6,4))
plt.plot(x,y1,x,y2)
plt.fill_between(x,y1,y2,facecolor='k',alpha=0.2)
plt.text(1.5,0,'包围部分',fontsize=20)
plt.title('画出包围部分',fontsize=16)

在这里插入图片描述

散点图

plt.scatter(x,y,s=None,c=None,marker=None,alpha=None)

其中 s 为每一个点的大小,若传入的是一个列表或者 array,则array匹配每一个点的大小; c 表示点的颜色,若传入的是列表或者 array,则匹配每一个点的颜色

from sklearn.datasets import make_gaussian_quantiles  
X, y = make_gaussian_quantiles(n_samples=300,n_features=2, n_classes=2)  #产生数据集
X0 = X[y.ravel()==0]
plt.scatter(X0[:, 0], X0[:, 1], marker='o')  
X1 = X[y.ravel()==1]
plt.scatter(X1[:, 0], X1[:, 1], marker='x') 

散点图结果

柱状图

plt.bar(x,height,width,color)
其中 height 是柱状图的高度,即 y;

x = np.arange(10)
y1 = np.random.randn(10)
y2 = np.random.randn(10)
fig = plt.figure(figsize=(6,4))
plt.bar(x,y1,width=0.35,color='g')
plt.bar(x+0.35,y2,width=0.35,color='b')
plt.xlabel('x',fontsize=16)
plt.ylabel('y',fontsize=16)

在这里插入图片描述

饼状图

plt.pie(x,labels=None,explode=None,colors=None,autopct=None)
其中:x 为待表示数据;label 接受一个 array,分别对应 x 的标签,explode 接受 array,表示饼状图离圆心的距离(用半径的百分比表示);colors 可以接受 array,表示每一个饼的颜色,autopct 是设置比例的表示方法,如 %1.1f %%(第二个 % 是为了转意)

x = [15,20,30,40]
explode = [0.05]*len(x)
autopct = '%1.1f %%'
labels = ['one','two','three','four']
fig = plt.figure(figsize=(6,4))
patches,l_text,p_text = plt.pie(x,labels=labels,explode=explode,autopct=autopct)
#l_text,p_text 是为了设置饼状图的文本。l_text 是labels的文本,p_text 是图内部的文本(比例)
for t in l_text:t.set_size(30)
for t in p_text:t.set_size(20)

在这里插入图片描述

箱型图

plt.boxplot(df,sym,meanline)
df:为箱型图绘制的数据,以列为单位进行绘制
sym:为异常点的形状
meanline:是否展示平均线

import pandas as pd
df = pd.DataFrame(np.random.randn(5,4),columns=['A','B','C','D'])
fig = plt.figure(figsize=(6,4))
plt.boxplot(df,sym='o',meanline=True)

在这里插入图片描述
若要设置 xticks,则需要用到 ax,如下:

df = pd.DataFrame(np.random.randn(5,4),columns=['A','B','C','D'])
fig = plt.figure(figsize=(6,4))
ax = plt.subplot()ax.boxplot(df,sym='o')
ax.set_xticklabels(['A','B','C','D'])

频率直方图

import pandas as pd
x = np.random.normal(0,1,size=(100))
fig = plt.figure(figsize=(6,4))
bin_num = 10
plt.hist(x,bin_num)

在这里插入图片描述

相关内容

热门资讯

常用商务英语口语   商务英语是以适应职场生活的语言要求为目的,内容涉及到商务活动的方方面面。下面是小编收集的常用商务...
六年级上册英语第一单元练习题   一、根据要求写单词。  1.dry(反义词)__________________  2.writ...
复活节英文怎么说 复活节英文怎么说?复活节的英语翻译是什么?复活节:Easter;"Easter,anniversar...
2008年北京奥运会主题曲 2008年北京奥运会(第29届夏季奥林匹克运动会),2008年8月8日到2008年8月24日在中华人...
英语道歉信 英语道歉信15篇  在日常生活中,道歉信的使用频率越来越高,通过道歉信,我们可以更好地解释事情发生的...
六年级英语专题训练(连词成句... 六年级英语专题训练(连词成句30题)  1. have,playhouse,many,I,toy,i...
上班迟到情况说明英语   每个人都或多或少的迟到过那么几次,因为各种原因,可能生病,可能因为交通堵车,可能是因为天气冷,有...
小学英语教学论文 小学英语教学论文范文  引导语:英语教育一直都是每个家长所器重的,那么有关小学英语教学论文要怎么写呢...
英语口语学习必看的方法技巧 英语口语学习必看的方法技巧如何才能说流利的英语? 说外语时,我们主要应做到四件事:理解、回答、提问、...
四级英语作文选:Birth ... 四级英语作文范文选:Birth controlSince the Chinese Governmen...
金融专业英语面试自我介绍 金融专业英语面试自我介绍3篇  金融专业的学生面试时,面试官要求用英语做自我介绍该怎么说。下面是小编...
我的李老师走了四年级英语日记... 我的李老师走了四年级英语日记带翻译  我上了五个学期的小学却换了六任老师,李老师是带我们班最长的语文...
小学三年级英语日记带翻译捡玉... 小学三年级英语日记带翻译捡玉米  今天,我和妈妈去外婆家,外婆家有刚剥的`玉米棒上带有玉米籽,好大的...
七年级英语优秀教学设计 七年级英语优秀教学设计  作为一位兢兢业业的人民教师,常常要写一份优秀的教学设计,教学设计是把教学原...
我的英语老师作文 我的英语老师作文(通用21篇)  在日常生活或是工作学习中,大家都有写作文的经历,对作文很是熟悉吧,...
英语老师教学经验总结 英语老师教学经验总结(通用19篇)  总结是指社会团体、企业单位和个人对某一阶段的学习、工作或其完成...
初一英语暑假作业答案 初一英语暑假作业答案  英语练习一(基础训练)第一题1.D2.H3.E4.F5.I6.A7.J8.C...
大学生的英语演讲稿 大学生的英语演讲稿范文(精选10篇)  使用正确的写作思路书写演讲稿会更加事半功倍。在现实社会中,越...
VOA美国之音英语学习网址 VOA美国之音英语学习推荐网址 美国之音网站已经成为语言学习最重要的资源站点,在互联网上还有若干网站...
商务英语期末试卷 Part I Term Translation (20%)Section A: Translate ...