日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

matplotlib与seaborn的一些使用

發布時間:2024/7/23 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 matplotlib与seaborn的一些使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.plt.plot畫線畫點?

a = np.array([[1, 2], [3, 4]]) print(a[:, 0]) plt.plot(a[:, 0], a[:, 1]) plt.show() plt.plot(a[:, 0], a[:, 1], 'o',color='red') plt.show()#添加風格 plt.plot(x,y,color='red',linewidth=1.0,linestyle='--') #設置x軸范圍 plt.xlim((-1,2)) # 設置y軸范圍 plt.ylim((-2, 3))

#標題變為figure3,長寬為8,5 plt.figure(num=3,figsize=(8,5)) a = np.array([[1, 2], [3, 4]]) plt.plot(a[:, 0], a[:, 1]) plt.show()

2.plt.scatter散點圖

n=1024 X=np.random.normal(0,1,n) Y = np.random.normal(0, 1, n) print(Y) T=np.arctan2(Y,X) #for color value #c表示顏色序列 plt.scatter(X,Y,s=75,c=T,alpha=0.5) #不要坐標刻度 plt.xticks(()) plt.yticks(()) plt.show()

3.生成柱狀圖

方法1:

"""生成柱狀圖""" def write_bar():num_list = [0.42974282, 0.08665644 ,0.39311899 ,0.09048176]name_list=['pig_length','pig_photo_center','disk_length','disk_photo_center']plt.ylabel('feature importance')plt.bar(range(len(num_list)), num_list,tick_label=name_list)# plt.xticks(name_list,rotation = 20)plt.xticks(rotation = 20)plt.show()

方法2:

name_list = ['detected', 'Undetectable'] num_list = [91,134-91] rects = plt.bar(range(len(num_list)), num_list, color='gr') # X軸標題 index = [0, 1] plt.xticks(index, name_list) plt.ylabel('photos') # X軸標簽 for rect in rects:height = rect.get_height()plt.text(rect.get_x() + rect.get_width() / 2, height, str(height), ha='center', va='bottom') plt.show()

方法3(推薦使用):

import numpy as np import pandas as pd import matplotlib.pyplot as plt_, count_values = np.unique([1, 1, 2, 2, 2, 3], return_counts=True) print('count_values:', count_values)class_names = ['mountain', 'street', 'glacier']#柱狀圖 pd.DataFrame({'train': count_values,'test': count_values},index=class_names).plot.bar() plt.show()

4.直方圖

import numpy as npimport matplotlib.mlab as mlabimport matplotlib.pyplot as plt# example datamu = 100 # mean of distributionsigma = 15 # standard deviation of distributionx = mu + sigma * np.random.randn(10000)num_bins = 50# the histogram of the datan, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='blue', alpha=0.5)# add a 'best fit' liney = mlab.normpdf(bins, mu, sigma)plt.plot(bins, y, 'r--')plt.xlabel('Smarts')plt.ylabel('Probability')plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')## Tweak spacing to prevent clipping of ylabelplt.subplots_adjust(left=0.15)plt.show()import seaborn as snssns.set_palette("hls") # 設置所有圖的顏色,使用hls色彩空間sns.distplot(x, kde_kws={'label':"label"},color="r", bins=30, kde=True)plt.xlabel('Smarts')plt.ylabel('Probability')plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')plt.show()

示例:產生均值為0,標準差為0.1的10000個點?

mu, sigma = 0, 0.1 y=np.random.normal(mu, sigma,10000) count, x, ignored=plt.hist(y,bins=50,density=True) plt.plot(x, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (x - mu)**2 / (2 * sigma**2) ), linewidth=2, color='r') plt.show()

"""長度誤差直方圖""" pig_length_list = list(map(float, pig_length_list)) pig_error_list = list(map(float, pig_error_list)) print(len(pig_error_list)) # sns.distplot(pig_error_list, hist=True, kde=True) r=plt.hist2d(pig_length_list,pig_error_list,bins=(30,30),cmap=plt.cm.jet) plt.xlabel('length') plt.ylabel('Abs Error') plt.colorbar(r[3]) plt.show()

from matplotlib import colors r=plt.hist2d(pig_length_list,pig_error_list,bins=(30,30),cmap=plt.cm.jet,norm=colors.LogNorm()) plt.xlabel('length') plt.ylabel('ABS Error') plt.colorbar(r[3]) plt.show()

pig_length_list = list(map(float, pig_length_list)) pig_error_list = list(map(float, pig_error_list)) print(len(pig_error_list)) ax = sns.kdeplot(pig_length_list, pig_error_list, cmap=plt.cm.jet, shade=True, cbar=True, n_levels=30) ax.set(xlabel='real length', ylabel='length abs error',ylim=(-20, 20)) # r=plt.hist2d(pig_length_list,pig_error_list,bins=(30,30),cmap=plt.cm.jet) # plt.xlabel('length') # plt.ylabel('ABS Error') # plt.colorbar(r[3]) plt.show()

"""長度誤差密度圖""" pig_length_list = list(map(float, pig_length_list)) pig_error_list = list(map(float, pig_error_list)) print(len(pig_error_list)) ax = sns.kdeplot(pig_length_list, pig_error_list, cmap=plt.cm.jet, shade=True, cbar=True, n_levels=30,shade_lowest=False) ax.set(xlabel='real length', ylabel='length abs error',ylim=(-20, 20)) # from matplotlib import colors # r=plt.hist2d(pig_length_list,pig_error_list,bins=(30,30),cmap=plt.cm.jet,norm=colors.LogNorm()) # plt.xlabel('length') # plt.ylabel('ABS Error') # plt.colorbar(r[3]) plt.show()

5.繪制3D曲線

from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) X = np.arange(-4, 4, 0.25) Y = np.arange(-4, 4, 0.25) X, Y = np.meshgrid(X, Y) R = X**2 +Y**2 # Z = np.sin(R)# 具體函數方法可用 help(function) 查看,如:help(ax.plot_surface) ax.plot_surface(X, Y, R, rstride=1, cstride=1, cmap='rainbow')plt.show()

from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) X = np.arange(-4, 4, 0.25) Y = np.arange(-4, 4, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X ** 2 + Y ** 2)# 具體函數方法可用 help(function) 查看,如:help(ax.plot_surface) #rstride行跨 cstride列跨 ax.plot_surface(X, Y, R, rstride=1, cstride=1, cmap='rainbow')#投影 offset把圖形壓縮到xoy里面,z=0的位置 ax.contourf(X,Y,R,zdir='z',offset=0,cmap='rainbow') ax.set_zlim(0,4) plt.show()

from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) X = np.arange(-4, 4, 0.25) Y = np.arange(-4, 4, 0.25) X, Y = np.meshgrid(X, Y) R = X**2 - Y**2 # Z = np.sin(R)# 具體函數方法可用 help(function) 查看,如:help(ax.plot_surface) ax.plot_surface(X, Y, R, rstride=1, cstride=1, cmap='rainbow')plt.show()

import numpy as np import matplotlib.pyplot as plt import math import mpl_toolkits.mplot3d# x, y = np.mgrid[-2:2:200j, -2:2:200j] x = np.arange(-6, 6, 0.25) y = np.arange(-6, 6, 0.25) x, y = np.meshgrid(x, y) # z=(1/2*math.pi*3**2)*np.exp(-(x**2+y**2)/2*3**2) z = np.exp(-(x**2+y**2 - 0)/2*1**2) ax = plt.subplot(111, projection='3d') ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap='rainbow', alpha=0.9)#繪面ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') plt.show()

X = np.arange(-4, 4, 0.25) Y = np.arange(-4, 4, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2)# 具體函數方法可用 help(function) 查看,如:help(ax.plot_surface) plt.imshow(R) plt.colorbar() plt.show()

6.3D直方圖

from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as npfig = plt.figure() ax = fig.add_subplot(111, projection='3d') x, y = np.random.rand(2, 100) * 4 hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])# Construct arrays for the anchor positions of the 16 bars. # Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos, # ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid # with indexing='ij'. xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25) xpos = xpos.flatten('F') ypos = ypos.flatten('F') zpos = np.zeros_like(xpos)# Construct arrays with the dimensions for the 16 bars. dx = 0.5 * np.ones_like(zpos) dy = dx.copy() dz = hist.flatten()ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')plt.show()

7.3D條狀圖

from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as npfig = plt.figure() ax = fig.add_subplot(111, projection='3d') for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):xs = np.arange(20)ys = np.random.rand(20)# You can provide either a single color or an array. To demonstrate this,# the first bar of each set will be colored cyan.cs = [c] * len(xs)cs[0] = 'c'ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z')plt.show()

8.plt.legend?

steps = np.linspace(0, np.pi*2, 256, dtype=np.float32) sin_np = np.sin(steps) print(sin_np.shape) cos_np = np.cos(steps) plt.figure() plt.title('Sin and Cos',fontsize='18') plt.plot(steps,sin_np,'r-',label='sin') plt.plot(steps,cos_np,'b-',label='cos') plt.legend(loc='best') plt.show()

9.plt.subplot?

x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x)# Set up a subplot grid that has height 2 and width 1, # and set the first such subplot as active. plt.subplot(2, 1, 1) # Make the first plot plt.plot(x, y_sin) plt.title('Sine') # Set the second subplot as active, and make the second plot. plt.subplot(2, 1, 2) plt.plot(x, y_cos) plt.title('Cosine') # Show the figure. plt.show()

10.等比顯示

plt.gca().set_aspect('equal')

11.畫餅狀圖:

#餅狀圖 plt.pie(count_values,#和類別數相等的labels=class_names,#加上labelautopct='%1.1f%%')#加上百分比 plt.axis('equal') plt.title('Proportion of each observed category') plt.savefig('./pie.jpg') plt.show()

import numpy as np import matplotlib.pyplot as plty1 = [] y2 = [] y3 = [] years = [] for i in range(7):years.append(i)y1.append(round(25000*np.exp(0.05*i), 2))y2.append(round(25000 * (1 + 0.06) ** (i),2))y3.append(round(25000 * (1+0.02)**(4*i),2))print(y1) print(y2) print(y3) plt.plot(years, y1, color='red', linewidth=1.0, label='option 1')#, linestyle='--') plt.plot(years, y2, color='green', linewidth=1.0, label='option 2')#, linestyle='--') plt.plot(years, y3, color='blue', linewidth=1.0, label='option 3')#, linestyle='--') #設置x軸范圍 plt.xlim((0, 10)) # 設置y軸范圍 plt.ylim((25000, 40000)) plt.ylabel('Principal and interest') plt.xlabel('Year') plt.legend(loc='best') # plt.yticks(np.linspace(25000, 40000, 500)) plt.savefig('./hu1.jpg') plt.show()plt.figure(figsize=(20, 8)) # plt.title('Principal and interest') col = ['year' + str(i) for i in years] row = ['op1', 'op2', 'op3'] vals = [] vals.append(y1) vals.append(y2) vals.append(y3) vals = np.array(vals) # colors = ["#e41a1c","#377eb8","#00ccff"]*7 rcolors = plt.cm.BuPu(np.full(3, 0.1)) ccolors = plt.cm.BuPu(np.full(7, 0.1)) tab = plt.table(cellText=vals,colLabels=col,rowLabels=row,rowColours=rcolors,colColours=ccolors,loc='center',cellLoc='center',rowLoc='center') tab.scale(1, 2) plt.axis('off') plt.savefig('./hu2.jpg') plt.show()op1_interest = y1[-1] - 25000 op2_interest = y2[-1] - 25000 op3_interest = y3[-1] - 25000 def plot_pie(interest, name):plt.figure()plt.title(name)patches, texts, autotexts = plt.pie(x=[interest, 25000],#指定繪圖數據colors=["#d5695d", "#5d8ca8"],labels=['Total interest', 'Initial investment'],autopct='%.2f%%',)plt.legend(patches, ['Total interest', 'Initial investment'], # 添加圖例# title="Pie Learning",loc="best",# fontsize=15,bbox_to_anchor=(1, 0, 0.5, 1))plt.savefig('./hu+{}.jpg'.format(name))plt.show() plot_pie(op1_interest, 'option1') plot_pie(op2_interest, 'option2') plot_pie(op3_interest, 'option3')

?

12.生成兩類數據

import torch import matplotlib.pyplot as plt from torch import nn, optim from torch.autograd import Variableimport numpy as npdef produce_data():# 假數據n_data = torch.ones(100, 2) # 數據的基本形態x0 = torch.normal(2 * n_data, 1) # 類型0 x data (tensor), shape=(100, 2)y0 = torch.zeros(100) # 類型0 y data (tensor), shape=(100, 1)x1 = torch.normal(-2 * n_data, 1) # 類型1 x data (tensor), shape=(100, 1)y1 = torch.ones(100) # 類型1 y data (tensor), shape=(100, 1)print(x0.shape)# 注意 x, y 數據的數據形式是一定要像下面一樣 (torch.cat 是在合并數據)x = torch.cat((x0, x1), 0).type(torch.FloatTensor) # FloatTensor = 32-bit floatingprint(x.shape)y = torch.cat((y0, y1), 0).type(torch.FloatTensor) # LongTensor = 64-bit integerprint(y.shape)# 畫圖plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn')plt.show()return x, y if __name__ == '__main__':produce_data()

13.plot的一些應用

import numpy as np import matplotlib.pyplot as plt import matplotlib x = np.arange(-4,4,0.5) # print(x) # fname 為 你下載的字體庫路徑,注意 SimHei.ttf 字體的路徑 zhfont1 = matplotlib.font_manager.FontProperties(fname='/usr/share/fonts/truetype/arphic/uming.ttc') plt.rcParams['xtick.direction'] = 'in'#將x周的刻度線方向設置向內 plt.rcParams['ytick.direction'] = 'in'#將y軸的刻度方向設置向內plt.axis([-3, 3, -2, 3]) # plt.title("Matplotlib demo") plt.xlabel("輸入",fontproperties=zhfont1) plt.ylabel("輸出",fontproperties=zhfont1)sigmoid_y = 1/(1+np.exp(-x)) print(sigmoid_y)plt.plot(x,sigmoid_y,'s',color='black',label='Sigmoid') # plt.show()tanh_y = (np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x)) print(tanh_y) # plt.rcParams['xtick.direction'] = 'in'#將x周的刻度線方向設置向內 # plt.rcParams['ytick.direction'] = 'in'#將y軸的刻度方向設置向內 plt.plot(x,tanh_y,'.-',color='black',label='Tanh') # plt.show()relu_y = [i if i>0 else 0 for i in x ] print(relu_y) # plt.rcParams['xtick.direction'] = 'in'#將x周的刻度線方向設置向內 # plt.rcParams['ytick.direction'] = 'in'#將y軸的刻度方向設置向內 plt.plot(x,relu_y,'-',color='black',label='Relu') # plt.show()elu_y = [i if i>0 else 0.3*(np.exp(i)-1) for i in x ] print(elu_y) # plt.rcParams['xtick.direction'] = 'in'#將x周的刻度線方向設置向內 # plt.rcParams['ytick.direction'] = 'in'#將y軸的刻度方向設置向內 plt.plot(x,elu_y, '^',color='black',label='Elu') plt.legend(loc='best') # plt.show() plt.savefig('hha.jpg')

14-1.ax畫3d圖與線段等比縮放

import matplotlib.pyplot as plt ax = plt.subplot(111, projection='3d')point_a = np.array([[1, 2, 3],[2, 2, 2]]).astype(np.float32) point_ori_a_length = np.linalg.norm(point_a[1, :] - point_a[0, :])point_b = np.array([[2, 2, 2],[5, 5, 5]]).astype(np.float32) point_ori_b_length = np.linalg.norm(point_b[1, :] - point_b[0, :]) print('==point_ori_a_length:', point_ori_a_length) print('==point_ori_b_length:', point_ori_b_length) print('==point_ori_b_length / point_ori_a_length:', point_ori_b_length / point_ori_a_length)ax.plot(point_a[:, 0], point_a[:, 1], point_a[:, 2]) ax.plot(point_b[:, 0], point_b[:, 1], point_b[:, 2]) plt.xlim(1, 6) plt.ylim(1, 6) ax.set_zlim(1, 6) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') plt.show()ax = plt.subplot(111, projection='3d')point_a[1, :] = point_a[0, :] + (point_a[1, :] - point_a[0, :]) / point_ori_a_lengthpoint_b[1, :] = point_b[0, :] + (point_b[1, :] - point_b[0, :]) / point_ori_a_length dis_ = point_b[1, :] - point_b[0, :] point_b[0, :] = point_a[1, :] point_b[1, :] = point_b[0, :] + dis_ point_now_a_length = np.linalg.norm(point_a[1, :] - point_a[0, :]) point_now_b_length = np.linalg.norm(point_b[1, :] - point_b[0, :]) print('==point_now_a_length:', point_now_a_length) print('==point_now_b_length:', point_now_b_length) print('==point_now_b_length / point_now_a_length:', point_now_b_length / point_now_a_length) ax.plot(point_a[:, 0], point_a[:, 1], point_a[:, 2]) ax.plot(point_b[:, 0], point_b[:, 1], point_b[:, 2]) plt.xlim(1, 6) plt.ylim(1, 6) ax.set_zlim(1, 6) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') plt.show()

??

??

14-2.顯示3d手同時用ax.text顯示序號

注意的是cv2放在plt后面

import matplotlib.pyplot as plt import cv2 import mpl_toolkits.mplot3d import numpy as npcamera_hand_right_3dkpts = np.array([[0.8647481799125671, -38.08830642700195, 335.964599609375], [0.6563963294029236, -38.625457763671875, 332.47576904296875], [0.14763949811458588, -40.26291275024414, 328.74615478515625], [0.006336620077490807, -42.1802978515625, 326.2594909667969], [-0.3949889540672302, -43.737998962402344, 324.50811767578125], [1.0360386371612549, -44.29584503173828, 329.23480224609375], [1.794701099395752, -47.37247085571289, 327.18402099609375], [2.4282193183898926, -49.27631378173828, 326.35888671875], [3.095630407333374, -50.87310791015625, 325.6286926269531], [1.8775584697723389, -45.17683410644531, 330.75909423828125], [3.0296430587768555, -48.540794372558594, 328.830810546875], [4.360949993133545, -50.52870178222656, 327.6854553222656], [5.470311641693115, -52.16162872314453, 326.7551574707031], [2.8303887844085693, -45.574363708496094, 332.34515380859375], [4.117491722106934, -48.58415603637695, 330.589111328125], [5.522796154022217, -50.38448715209961, 329.4515075683594], [6.774843692779541, -51.6481819152832, 328.4239196777344], [3.768697500228882, -45.72537612915039, 333.8792419433594], [4.950739860534668, -48.10667037963867, 332.6934814453125], [6.098034858703613, -49.30638885498047, 331.6702575683594], [7.019787788391113, -50.42774200439453, 330.9171142578125]]) camera_hand_right_3dkpts = camera_hand_right_3dkpts.transpose() print(camera_hand_right_3dkpts.shape) hand_edges = np.array([[0, 1], [1, 2], [2, 3], [3, 4],[0, 5], [5, 6], [6, 7], [7, 8],[0, 9], [9, 10], [10, 11], [11, 12],[0, 13], [13, 14], [14, 15], [15, 16],[0, 17], [17, 18], [18, 19], [19, 20]]) ax = plt.axes(projection='3d') for i, edge in enumerate(hand_edges):ax.plot(camera_hand_right_3dkpts[0, edge], camera_hand_right_3dkpts[1, edge], camera_hand_right_3dkpts[2, edge]) # ax.set_xlabel('x') # ax.set_ylabel('y') # ax.set_zlabel('z') # plt.xlim(-30, -42) # plt.ylim(-150, -154) # ax.set_zlim(70, 95) # axis_limit = 700 x_c = np.mean(camera_hand_right_3dkpts[0, :]) y_c = np.mean(camera_hand_right_3dkpts[1, :]) z_c = np.mean(camera_hand_right_3dkpts[2, :]) # axis_limit = 50 # # ax.set_xlim3d([x_c - axis_limit / 2, x_c + axis_limit / 2]) # ax.set_ylim3d([y_c - axis_limit / 2, y_c + axis_limit / 2]) # ax.set_zlim3d([3 * z_c / 4, z_c]) ax.set_aspect('auto') ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) ax.set_xticklabels(['x']) ax.set_yticklabels(['y']) ax.set_zticklabels(['z']) x_3d = camera_hand_right_3dkpts[0, :].transpose() y_3d = camera_hand_right_3dkpts[1, :].transpose() z_3d = camera_hand_right_3dkpts[2, :].transpose()ax.scatter(x_3d,y_3d,z_3d,marker='o',color=(0, 0, 1), # rgb ) for i, _ in enumerate(hand_edges):ax.text(x_3d[i], y_3d[i], z_3d[i], i) plt.show()

14-3.變換視角

plt坐標系如下左圖,而我們一般3d坐標是如下右圖有時候為了與2d圖片對上,將x,y變換到x,z方便查看,乘以一個矩陣變換一下.

vis_R = np.array([[1, 0, 0],[0, 0, -1],[0, 1, 0]])keypoints_3d[:, :3] = keypoints_3d[:, :3] @ vis_R

同時為了,將視角變化一下,在限定一下范圍

axis_azimuth = -90axis_elev = 0ax.view_init(elev=axis_elev,azim=axis_azimuth,)h = 2d_img_hw = 2d_img_wx_c = np.mean(x_3d)y_c = np.mean(y_3d)z_c = np.mean(z_3d)ax.set_xlim3d([x_c - w / 2, x_c + w / 2])# ax.set_ylim3d([y_c - h / 2, y_c + h / 2])ax.set_zlim3d([z_c - h / 2, z_c + h / 2])

不同視角的手,其中負號代碼逆時針轉

z0y0視角:                   z0y45視角:

??

z45y0視角:                   z45y45視角:?

?

?z-90y0視角:

?

??15.plt.text在點處寫文字

import matplotlib.pyplot as plt import numpy as npprecision = np.array([1. , 1. , 1. , 1. , 1. ,1. , 1. , 1. , 1. , 1. ,1. , 1. , 0.99883178, 0.99833749, 0.99833749,0.99833749, 0.99833749, 0.99833749, 0.99785484, 0.99785484,0.99785484, 0.99785484, 0.99785484, 0.99785484, 0.99785484,0.99785484, 0.99785484, 0.99785484, 0.99785484, 0.99785484,0.99785484, 0.99785484, 0.99785484, 0.99785484, 0.99785484,0.99785484, 0.99785484, 0.99785484, 0.99785484, 0.99785484,0.99785484, 0.99776999, 0.99776999, 0.99776999, 0.99776999,0.99776999, 0.99768465, 0.99768465, 0.99768465, 0.99768465,0.99768465, 0.99768465, 0.99768465, 0.99768465, 0.99768465,0.99768465, 0.99768465, 0.99768465, 0.99768465, 0.99768465,0.99768465, 0.99768465, 0.99768465, 0.997593 , 0.997593 ,0.997593 , 0.99744572, 0.99744572, 0.99730402, 0.99730402,0.99694439, 0.99677224, 0.99663965, 0.99650553, 0.99650553,0.99619338, 0.99587397, 0.99571615, 0.99540272, 0.99509893,0.99463807, 0.99403509, 0.99372494, 0.99293591, 0.99118943,0.98993795, 0.98874359, 0.98677335, 0.9854745 , 0.98343158,0.98100471, 0.9796647 , 0.97644179, 0.97417309, 0.97098646,0.96825863, 0.96327888, 0.95922441, 0.94851402, 0.82842664,0. ])recall = np.linspace(.0, 1.00, int(np.round((1.00 - .0) / .01)) + 1,endpoint=True) PrecisIndmaxscore = [86, 0.7205873131752014] APmaxscore = 0.13149480521678925 iouThr = 0.5ap = sum(precision) / len(precision) x1 = recall[np.nonzero(precision)[0][-1]] y1 = precision[np.nonzero(precision)[0][-1]]plt.figure() plt.text(x1, y1, 'ApScore: ' + str(APmaxscore)[:5], fontsize=8) if PrecisIndmaxscore[0] != -1:x2 = recall[PrecisIndmaxscore[0]]y2 = precision[PrecisIndmaxscore[0]]plt.text(x2, y2, 'PScore: ' + str(PrecisIndmaxscore[-1])[:5], fontsize=8)plt.title('IOU={}'.format(str(iouThr)[:4])) plt.xlabel("Recall") plt.ylabel("Precision") plt.plot(recall, precision, label='AP: ' + str(ap)[:5])#marker='o') plt.legend() # plt.savefig(os.path.join(savepath, "iou_{:2}.jpg".format(str(iouThrs[i])[:4]))) plt.show()

15.plt.sublpot

畫多個圖在一個圖上

import matplotlib.pyplot as plt import numpy as np import seaborn as snslengths = np.random.randint(0, 10, 1000) plt.figure(figsize=(12.8, 9.6)) #1280*960 plt.subplot(2, 2, 1, frameon=False) # 兩行兩列,位置是1的子圖 plt.title('One') plt.xlabel('x1') plt.ylabel('y1') sns.set_palette("hls") # 設置所有圖的顏色,使用hls色彩空間 sns.distplot(lengths, kde_kws={'label': "label"}, color="r", bins=30, kde=True)plt.subplot(2, 2, 2, frameon=False)# 兩行兩列,位置是1的子圖 plt.title('Two') plt.xlabel('x1') plt.ylabel('y1') sns.set_palette("hls") # 設置所有圖的顏色,使用hls色彩空間 sns.distplot(lengths, kde_kws={'label': "label"}, color="r", bins=30, kde=True)plt.show()

參考:

Python--matplotlib繪圖可視化知識點整理 - 止戰 - 博客園

Intel Image Classification (CNN - Keras) | Kaggle

總結

以上是生活随笔為你收集整理的matplotlib与seaborn的一些使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。