Python 各种画图

这篇具有很好参考价值的文章主要介绍了Python 各种画图。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

说实话,Python 画图和 Matlab 画图十分相似『Matlab 转战 Python』—— 沃兹·基硕德

Part.I 基础知识

Chap.I 快应用

  • Python 常用线型 + 点符号 + 颜色汇总
  • Python 中图例 Legend 的调整
  • Python 修改 x/y ticks
  • Python 绘图字体与位置控制

下面是『进阶使用』:

  • Python 让多图排版更加美观
  • Python 箱型图的绘制并提取特征值

Chap.II 常用语句

下面是一些基本的绘图语句:

import matplotlib.pyplot as plt			# 导入模块

plt.style.use('ggplot')					# 设置图形的显示风格
fig=plt.figure(1)						# 新建一个 figure1
fig=plt.figure(figsize=(12,6.5),dpi=100,facecolor='w')
fig.patch.set_alpha(0.5)				# 设置透明度为 0.5
font1 = {'weight' : 60, 'size' : 10}	# 创建字体,设置字体粗细和大小
ax1.set_xlim(0,100)						# 设置 x 轴最大最小刻度
ax1.set_ylim(-0.1,0.1)					# 设置 y 轴最大最小刻度
plt.xlim(0,100)  						# 和上面效果一样
plt.ylim(-1,1)
ax1.set_xlabel('X name',font1)			# 设置 x 轴名字
ax1.set_ylabel('Y name',font1)			# 设置 y 轴名字
plt.xlabel('aaaaa')						# 设置 x 轴名字
plt.ylabel('aaaaa')						# 设置 y 轴名字
ax.yaxis.set_label_position("right") 	# y 轴标签右侧显示
ax.yaxis.tick_right() 					# y 轴 ticks 右侧显示
plt.grid(True)					 		# 增加格网
plt.grid(axis="y")						# 只显示横向格网
plt.grid(axis="x")						# 只显示纵向格网
ax1.axhline(0, linestyle='--', color='gray')	# 只显示 y=0 这一条横向格网
ax1.axvline(0, linestyle='--', color='k') 		# 只显示 x=0 这一条纵向格网
ax=plt.gca()							# 获取当前axis,
fig=plt.gcf()							# 获取当前figures
plt.gca().set_aspect(1)					# 设置横纵坐标单位长度相等
plt.text(x,y,string)					# 在 x,y 处加入文字注释
plt.gca().set_xticklabels(labels, rotation=30, fontsize=16) # 指定在刻度上显示的内容
plt.xticks(ticks, labels, rotation=30, fontsize=15)   # 上面两句合起来
plt.legend(['Float'],ncol=1,prop=font1,frameon=False)	# 设置图例 列数、去掉边框、更改图例字体
plt.title('This is a Title')			# 图片标题
plt.show()								# 显示图片,没这行看不见图
plt.savefig(path, dpi=300)				# 保存图片,dpi可控制图片清晰度,越高越好
# 在保存图片前可不要 plt.show() 不然你保存的图片中啥也没有。
plt.savefig(path, format='svg',dpi=300) # 保存为 svg 格式的矢量图
# Python 不能保存 emf, 可以存成 svg,然后用 visio 打开,另存为 emf,再粘贴到 word 中
plt.savefig(path, format='svg', bbox_inches='tight', pad_inches=0, dpi=300)
# 也可以将图片保存为 pdf,一是 PDF 可以编辑,二是 pdf 也可以用别的软件保存为 emf,贴到 word 里面。
plt.savefig(path, format='pdf', bbox_inches='tight', pad_inches=0, dpi=300)
# 设置图片空白为最小,这很牛掰!!!
plt.rcParams['font.sans-serif'] = ['SimHei']  	# 添加这条可以让图形显示中文
mpl.rcParams['axes.unicode_minus'] = False		# 添加这条可以让图形显示负号
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')				#设置图片的右边框和上边框为不显示
# 子图
ax1=plt.subplot(3,1,1)
ax1.scatter(time,data[:,1],s=5,color='blue',marker='o') # size, color, 标记
ax1=plt.subplot(3,1,2)
...
# 控制图片边缘的大小
plt.subplots_adjust(left=0, bottom=0, right=1, top=1, hspace=0.1,wspace=0.1)

# 设置坐标刻度朝向,暂未成功
plt.rcParams['xtick.direction'] = 'in'
ax = plt.gca()
ax.invert_xaxis() 
ax.invert_yaxis()

Part.II 画图样例

不要忘记 import plt

import matplotlib.pyplot as plt

下面是一些简单的绘图示例,上面快应用『进阶使用』部分会有些比较复杂的操作,感兴趣的可参看。

Chap.I 散点图

years = [2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019]
turnovers = [0.5, 9.36, 52, 191, 350, 571, 912, 1027, 1682, 2135, 2684]
plt.figure()
plt.scatter(years, turnovers, c='red', s=100, label='legend')
plt.xticks(range(2008, 2020, 3))
plt.yticks(range(0, 3200, 800))
plt.xlabel("Year", fontdict={'size': 16})
plt.ylabel("number", fontdict={'size': 16})
plt.title("Title", fontdict={'size': 20})
plt.legend(loc='best')
plt.show()

Python 各种画图

Chap.II 柱状图

X=[1,2,3,4,5]
Y=[0.2,0.6,0.1,0.8,0.4]
plt.bar(X,Y,color='b')
plt.show()

Python 各种画图

Chap.III 折线图

参考:https://blog.csdn.net/AXIMI/article/details/99308004

plt.rcParams['font.sans-serif'] = ['SimHei']  # 添加这条可以让图形显示中文
x_axis_data = [1, 2, 3, 4, 5]
y_axis_data = [1, 2, 3, 4, 5]
# plot中参数的含义分别是横轴值,纵轴值,线的形状,颜色,透明度,线的宽度和标签
plt.plot(x_axis_data, y_axis_data, 'ro-', color='#4169E1', alpha=0.8, linewidth=1, label='一些数字')
# 显示标签,如果不加这句,即使在plot中加了label='一些数字'的参数,最终还是不会显示标签
plt.legend(loc="upper right")
plt.xlabel('x轴数字')
plt.ylabel('y轴数字')
plt.show()

Python 各种画图

Chap.IV 概率分布直方图

主要通过函数plt.hist()来实现,

matplotlib.pyplot.hist(  
x, bins=10, range=None, normed=False,edgecolor='k',   
weights=None, cumulative=False, bottom=None,   
histtype=u'bar', align=u'mid', orientation=u'vertical',   
rwidth=None, log=False, color=None, label=None, stacked=False,   
hold=None, **kwargs)

其中,常用的参数及其含义如下:

  • bins:“直方条”的个数,一般可取20
  • range=(a,b):只考虑区间(a,b)之间的数据,绘图的时候也只绘制区间之内的
  • edgecolor=‘k’:给直方图加上黑色边界,不然看起来很难看(下面的例子就没加,所以很难看)
example_list=[]
n=10000
for i in range(n):
    tmp=[np.random.normal()]
    example_list.extend(tmp)
width=100
n, bins, patches = plt.hist(example_list,bins = width,color='blue',alpha=0.5)
X = bins[0:width]+(bins[1]-bins[0])/2.0
Y = n
maxn=max(n)
maxn1=int(maxn%8+maxn+8*2)
ydata=list(range(0,maxn1+1,maxn1//8))
yfreq=[str(i/sum(n)) for i in ydata]
plt.plot(X,Y,color='green')     #利用返回值来绘制区间中点连线
p1 = np.polyfit(X, Y, 7)        #利用7次多项式拟合,返回拟多项式系数,按照阶数从高到低排列
Y1 = np.polyval(p1,X)
plt.plot(X,Y1,color='red')
plt.xlim(-2.5,2.5)	
plt.ylim(0)
plt.yticks(ydata,yfreq)        #这条语句控制纵坐标是频数或频率,打开是频率,否则是频数
plt.legend(['midpoint','fitting'],ncol=1,frameon=False)
plt.show()

Python 各种画图
上面的图片中,绿线是直方图矩形的中点连线,红线是根据直方图的中点7次拟合的曲线。

Chap.V 累计概率分布曲线

累积分布函数(Cumulative Distribution Function),又叫分布函数,是概率密度函数的积分,能完整描述一个实随机变量X的概率分布。

example_list=[]
n=10000
for i in range(n):
    tmp=[np.random.normal()]
    example_list.extend(tmp)
width=50
n, bins, patches = plt.hist(example_list,bins = width,color='blue',alpha=0.5)
plt.clf()           # clear the figure
X = bins[0:width]+(bins[1]-bins[0])/2.0
bins=bins.tolist()
freq=[f/sum(n) for f in n]
acc_freq=[]
for i in range(0,len(freq)):
    if i==0:
        temp=freq[0]
    else:
        temp=sum(freq[:i+1])
    acc_freq.append(temp)
plt.plot(X,acc_freq,color='r')                    # Cumulative probability curve
yt=plt.yticks()
yt1=yt[0].tolist()
def to_percent(temp,position=0):          # convert float number to percent
    return '%1.0f'%(100*temp) + '%'
ytk1=[to_percent(i) for i in yt1 ]
plt.yticks(yt1,ytk1)
plt.ylim(0,1)
plt.show()

Python 各种画图

Chap.VI 概率分布直方图+累计概率分布图

参考:https://blog.csdn.net/qq_38412868/article/details/105319818
可以绘制概率分布直方图和累计概率曲线

笔者进行了一些的改编:

def draw_cum_prob_curve(data,bins=20,title='Distribution Of Errors',xlabel='The Error(mm)',pic_path=''):
    """
    plot Probability distribution histogram and Cumulative probability curve.
    
    > @param[in] data:          The error data
    > @param[in] bins:          The number of hist
    > @param[in] title:         The titile of the figure
    > @param[in] xlabel:        The xlable name
    > @param[in] pic_path:      The path where you want to save the figure
    return:     void
    """
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    from matplotlib.ticker import FuncFormatter
    from matplotlib.pyplot import MultipleLocator
    def to_percent(temp,position=0):          # convert float number to percent
        return '%1.0f'%(100*temp) + '%'
    fig, ax1 = plt.subplots(1, 1, figsize=(12, 6), dpi=100, facecolor='w')
    font1 = {'weight': 600, 'size': 15}
    
    n, bins, patches=ax1.hist(data,bins =bins, alpha = 0.65,edgecolor='k') # Probability distribution histogram
    yt=plt.yticks()
    yt1=yt[0].tolist()
    yt2=[i/sum(n) for i in yt1]
    ytk1=[to_percent(i) for i in yt2 ]
    plt.yticks(yt1,ytk1)
    X=bins[0:-1]+(bins[1]-bins[0])/2.0 
    bins=bins.tolist()
    freq=[f/sum(n) for f in n]
    acc_freq=[]
    for i in range(0,len(freq)):
        if i==0:
            temp=freq[0]
        else:
            temp=sum(freq[:i+1])
        acc_freq.append(temp)
    ax2=ax1.twinx()                         # double ylable
    ax2.plot(X,acc_freq)                    # Cumulative probability curve
    ax2.yaxis.set_major_formatter(FuncFormatter(to_percent))
    ax1.set_xlabel(xlabel,font1)
    ax1.set_title(title,font1)
    ax1.set_ylabel('Frequency',font1)
    ax2.set_ylabel("Cumulative Frequency",font1)
    #plt.savefig(pic_path,format='png', dpi=300)

调用示例:

example_list=[]
n=10000
for i in range(n):
    tmp=[np.random.normal()]
    example_list.extend(tmp)
tit='TEST'
xla='DATA'
draw_cum_prob_curve(example_list,50,tit,xla)
plt.show()

Python 各种画图文章来源地址https://www.toymoban.com/news/detail-408290.html

到了这里,关于Python 各种画图的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Matlab 用矩阵画图

    本文汇总了 Matlab 用矩阵画图的几种方式。 关于 *.mat 文件 *.mat 文件是 matlab 的数据存储的标准格式,它是标准的二进制文件,还可以 ASCII 码形式保存和加载,在 MATLAB 中打开显示类似于单行 EXCEL 表格,加载和存储 mat 文件的语法: 用矩阵画图主要有如下几种方式: 下面是一

    2024年02月04日
    浏览(33)
  • matlab画图方法(持续更)

    创建画布:figure(1);         % 在同一个脚本文件里面,要想画多个图,需要给每个图编号,否则只会显示最后一个图 plot(x, y, \\\'o\\\', new_x, p, \\\'r--\\\') plot(x1,y1,x2,y2)          在各个分块位置创建坐标区。 subplot(m,n,p)当前图窗划分为 m×n 网格,并在 p 指定的位置创建坐标区。   

    2024年02月12日
    浏览(33)
  • matlab画图(一、柱状图)

    🐋 前言:柱状图利用柱子的高度,反映数据的差异。肉眼对高度差异很敏感,辨识效果非常好。柱状图的局限在于只适用中小规模的数据集。 🐬 目录: 一、数据获取 二、简单柱状图 三、分组柱状图 四、堆叠柱状图 一、数据获取 统计图的绘制离不开数据的支撑。一般来说

    2024年01月20日
    浏览(44)
  • Matlab(画图进阶)

            目录 大纲  1.特殊的Plots 1.1 loglog(双对数刻度图) ​1.3 plotyy(创建具有两个y轴的图形)  1.4yyaxis(创建具有两个y轴的图) 1.5 bar 3D条形图(bar3) 1.6 pie(饼图) 3D饼图 1.7 polar  2.Stairs And Ste阶梯图  3.Boxplot 箱型图和Error Bar误差条形图 3.1 boxplot  3.2 errorbar  4.fill(创建二维填充补片

    2024年02月10日
    浏览(29)
  • MATLAB画图相关操作

    axis([x_min,x_max,y_min,y_max]) %设置坐标轴范围 set(gca,‘XTick’,[-1:0.2:1]) % 设置坐标刻度 xlabel(‘x轴数据’); ylabel(‘y轴数据’); title(‘标题’); legend(‘图例1’,‘图例2’) % 去掉图例边框 legend boxoff; % 法2 设置坐标轴上下限:axis([xmin,xmax,ymin,ymax]); 设置图片大小:set(gcf,‘Position’,

    2024年02月06日
    浏览(30)
  • 【基本绘图注释函数】——MatLab画图

    在绘图中添加标签。此类函数的输入是一个字符串。MATLAB 中的字符串是用双引号 (\\\") 引起来的。 上面一部分画图代码这里省略 为y轴增加注释标签 增加图例。可以添加多个,参数之间用逗号隔开

    2024年02月16日
    浏览(30)
  • 【Matlab】画图时去掉某些图例

    在Matlab中,legend函数用于在图形中添加图例,以便更好地理解和解释数据。图例提供了与图形相关的标识,使观察者能够了解图形中不同元素的含义。 legend 函数的语法如下: 其中,每个标签参数代表一个数据系列或图形对象的名称。可以根据需要提供多个标签,每个标签将

    2024年02月15日
    浏览(36)
  • 添加背景图片画图matlab

    clear clc close all cd(\\\'C:UserswindDesktop\\\') ha=axes(\\\'units\\\',\\\'normalized\\\',\\\'position\\\',[0 0 1 1]); uistack(ha,\\\'down\\\') II=imread(\\\'PP.png\\\'); image(II) colormap gray set(ha,\\\'handlevisibility\\\',\\\'off\\\',\\\'visible\\\',\\\'off\\\'); x=-pi:0.1:pi; y=x.*sin(x.*cos(x)).*tan(x); plot(x,y,\\\'LineWidth\\\',2) set(gca,\\\'color\\\',\\\'none\\\') %这里以前自己没有注意

    2024年04月09日
    浏览(32)
  • Matlab 画图(全网最优质文章)

    只需要把bar换成bar3即可。 只需要把bar改成barh即可: 把pie该为pie3即可 在另一篇博客上有详解,如下: Matalb画雷达图(四行代码) 分别控制左右坐标就可以了,不要太简单。而且可以很多种图形任意搭配。 subplot函数: 使用方法:subplot(m,n,p)或者subplot(m n p)。 subplot是将

    2024年02月02日
    浏览(31)
  • MATLAB科学绘图-MATLAB画图技巧与实例(一):常用函数

    Matlab拥有强大的绘图功能,内置了很多绘图函数,只需要给出一些基本参数就能得到所需图形,这类函数称为 高层绘图函数 。 此外,Matlab还提供了直接对图形句柄进行操作的 低层绘图操作 。这类操作将图形的每个图形元素(如坐标轴、曲线、文字等)看做一个独立的对象

    2024年02月03日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包