半半路路网

Python 各种画图

Python 各种画图

文章目录

  • 一、各种基础知识
    • 1、画图常用语句
    • 2、各种线型 + 符号 + 颜色
    • 3、画图图例使用
  • 二、各种画图样例
    • 1、画图散点图
    • 2、各种柱状图
    • 3、画图折线图
    • 4、各种概率分布直方图
    • 5、画图累计概率分布曲线
    • 6、各种概率分布直方图+累计概率分布图

说实话,画图Python 画图和 Matlab 画图十分相似【Matlab 转战 Python】
Legend 图例:https://blog.csdn.net/HHG20171226/article/details/101302645
网格线设置:https://blog.csdn.net/weixin_41789707/article/details/81035997
字体设置:https://blog.csdn.net/HsinglukLiu/article/details/107821714

一、各种基础知识

1、画图常用语句

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

import matplotlib.pyplot as plt			# 导入模块plt.style.use('ggplot')					# 设置图形的显示风格fig=plt.figure(1)						# 新建一个 figure1fig=plt.figure(figsize=(12,6.5),dpi=100,facecolor='w')fig.patch.set_alpha(0.5)				# 设置透明度为 0.5font1 = { '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 轴名字plt.grid(True)					 		# 增加格网plt.grid(axis="y")						# 只显示横向格网plt.grid(axis="x")						# 只显示纵向格网ax=plt.gca()							# 获取当前axis,fig=plt.gcf()							# 获取当前figuresplt.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=600)				# 保存图片,dpi可控制图片清晰度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()

2、线型 + 符号 + 颜色

https://blog.csdn.net/Gou_Hailong/article/details/121787030

3、图例使用

https://blog.csdn.net/Gou_Hailong/article/details/121795267

二、画图样例

不要忘记 importplt

import matplotlib.pyplot as plt

1、散点图

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()

2、柱状图

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()

3、折线图

参考: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()

4、概率分布直方图

主要通过函数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=10000for i in range(n):    tmp=[np.random.normal()]    example_list.extend(tmp)width=100n, bins, patches = plt.hist(example_list,bins = width,color='blue',alpha=0.5)X = bins[0:width]+(bins[1]-bins[0])/2.0Y = nmaxn=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()


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

5、累计概率分布曲线

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

example_list=[]n=10000for i in range(n):    tmp=[np.random.normal()]    example_list.extend(tmp)width=50n, bins, patches = plt.hist(example_list,bins = width,color='blue',alpha=0.5)plt.clf()           # clear the figureX = bins[0:width]+(bins[1]-bins[0])/2.0bins=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 curveyt=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()

6、概率分布直方图+累计概率分布图

参考: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=10000for 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 各种画图