- A+
所屬分類:百科知識
散點密度圖是在散點圖的基礎上,計算了每個散點周圍分布了多少其他的點,并通過顏色表現出來。本文主要介紹了Python繪制散點密度圖的三種方式,需要的可以參考下
方式一
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import matplotlib.pyplot as pltimport numpy as npfrom scipy.stats import gaussian_kdefrom mpl_toolkits.axes_grid1 import make_axes_locatablefrom matplotlib import rcParamsconfig = {"font.family":'Times New Roman',"font.size": 16,"mathtext.fontset":'stix'}rcParams.update(config)# 讀取數據import pandas as pdfilename=r'F:/Rpython/lp37/testdata.xlsx'df2=pd.read_excel(filename)#讀取文件x=df2['data1'].valuesy=df2['data2'].valuesxy = np.vstack([x,y])z = gaussian_kde(xy)(xy)idx = z.argsort()x, y, z = x[idx], y[idx], z[idx]fig,ax=plt.subplots(figsize=(12,9),dpi=100)scatter=ax.scatter(x,y,marker='o',c=z,edgecolors='',s=15,label='LST',cmap='Spectral_r')cbar=plt.colorbar(scatter,shrink=1,orientation='vertical',extend='both',pad=0.015,aspect=30,label='frequency') #orientation='horizontal'font3={'family':'SimHei','size':16,'color':'k'}plt.ylabel("估計值",fontdict=font3)plt.xlabel("預測值",fontdict=font3)plt.savefig('F:/Rpython/lp37/plot70.png',dpi=800,bbox_inches='tight',pad_inches=0)plt.show() |


方式二
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
from statistics import meanimport matplotlib.pyplot as pltfrom sklearn.metrics import explained_variance_score,r2_score,median_absolute_error,mean_squared_error,mean_absolute_errorfrom scipy import statsimport numpy as npfrom matplotlib import rcParamsconfig = {"font.family":'Times New Roman',"font.size": 16,"mathtext.fontset":'stix'}rcParams.update(config)def scatter_out_1(x,y): ## x,y為兩個需要做對比分析的兩個量。????# ==========計算評價指標==========????BIAS = mean(x - y)????MSE = mean_squared_error(x, y)????RMSE = np.power(MSE, 0.5)????R2 = r2_score(x, y)????MAE = mean_absolute_error(x, y)????EV = explained_variance_score(x, y)????print('==========算法評價指標==========')????print('BIAS:', '%.3f' % (BIAS))????print('Explained Variance(EV):', '%.3f' % (EV))????print('Mean Absolute Error(MAE):', '%.3f' % (MAE))????print('Mean squared error(MSE):', '%.3f' % (MSE))????print('Root Mean Squard Error(RMSE):', '%.3f' % (RMSE))????print('R_squared:', '%.3f' % (R2))????# ===========Calculate the point density==========????xy = np.vstack([x, y])????z = stats.gaussian_kde(xy)(xy)????# ===========Sort the points by density, so that the densest points are plotted last===========????idx = z.argsort()????x, y, z = x[idx], y[idx], z[idx]????def best_fit_slope_and_intercept(xs, ys):????????m = (((mean(xs) * mean(ys)) - mean(xs * ys)) / ((mean(xs) * mean(xs)) - mean(xs * xs)))????????b = mean(ys) - m * mean(xs)????????return m, b????m, b = best_fit_slope_and_intercept(x, y)????regression_line = []????for a in x:????????regression_line.append((m * a) + b)????fig,ax=plt.subplots(figsize=(12,9),dpi=600)????scatter=ax.scatter(x,y,marker='o',c=z*100,edgecolors='',s=15,label='LST',cmap='Spectral_r')????cbar=plt.colorbar(scatter,shrink=1,orientation='vertical',extend='both',pad=0.015,aspect=30,label='frequency')????plt.plot([0,25],[0,25],'black',lw=1.5)? # 畫的1:1線,線的顏色為black,線寬為0.8????plt.plot(x,regression_line,'red',lw=1.5)????? # 預測與實測數據之間的回歸線????plt.axis([0,25,0,25])? # 設置線的范圍????plt.xlabel('OBS',family = 'Times New Roman')????plt.ylabel('PRE',family = 'Times New Roman')????plt.xticks(fontproperties='Times New Roman')????plt.yticks(fontproperties='Times New Roman')????plt.text(1,24, '$N=%.f$' % len(y), family = 'Times New Roman') # text的位置需要根據x,y的大小范圍進行調整。????plt.text(1,23, '$R^2=%.3f$' % R2, family = 'Times New Roman')????plt.text(1,22, '$BIAS=%.4f$' % BIAS, family = 'Times New Roman')????plt.text(1,21, '$RMSE=%.3f$' % RMSE, family = 'Times New Roman')????plt.xlim(0,25)????????????????????????????????? # 設置x坐標軸的顯示范圍????plt.ylim(0,25)????????????????????????????????? # 設置y坐標軸的顯示范圍????plt.savefig('F:/Rpython/lp37/plot71.png',dpi=800,bbox_inches='tight',pad_inches=0)????plt.show() |

方式三
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
import pandas as pdimport numpy as npfrom scipy import optimizeimport matplotlib.pyplot as pltfrom matplotlib import cmfrom matplotlib.colors import Normalizefrom scipy.stats import gaussian_kdefrom matplotlib import rcParamsconfig={"font.family":'Times New Roman',"font.size":16,"mathtext.fontset":'stix'}rcParams.update(config)# 讀取數據filename=r'F:/Rpython/lp37/testdata.xlsx'df2=pd.read_excel(filename)#讀取文件x=df2['data1'].values.ravel()y=df2['data2'].values.ravel()N = len(df2['data1'])#繪制擬合線x2 = np.linspace(-10,30)y2 = x2def f_1(x,A,B):????return A*x + BA1,B1 = optimize.curve_fit(f_1,x,y)[0]y3 = A1*x + B1# Calculate the point densityxy = np.vstack([x,y])z = gaussian_kde(xy)(xy)norm = Normalize(vmin = np.min(z), vmax = np.max(z))#開始繪圖fig,ax=plt.subplots(figsize=(12,9),dpi=600)scatter=ax.scatter(x,y,marker='o',c=z*100,edgecolors='',s=15,label='LST',cmap='Spectral_r')cbar=plt.colorbar(scatter,shrink=1,orientation='vertical',extend='both',pad=0.015,aspect=30,label='frequency')cbar.ax.locator_params(nbins=8)cbar.ax.set_yticklabels([0.005,0.010,0.015,0.020,0.025,0.030,0.035])#0,0.005,0.010,0.015,0.020,0.025,0.030,0.035ax.plot(x2,y2,color='k',linewidth=1.5,linestyle='--')ax.plot(x,y3,color='r',linewidth=2,linestyle='-')fontdict1 = {"size":16,"color":"k",'family':'Times New Roman'}ax.set_xlabel("PRE",fontdict=fontdict1)ax.set_ylabel("OBS",fontdict=fontdict1)# ax.grid(True)ax.set_xlim((0,25))ax.set_ylim((0,25))ax.set_xticks(np.arange(0,25.1,step=5))ax.set_yticks(np.arange(0,25.1,step=5))plt.savefig('F:/Rpython/lp37/plot72.png',dpi=800,bbox_inches='tight',pad_inches=0)plt.show() |



到此這篇關于Python繪制散點密度圖的三種方式詳解的文章就介紹到這了
歷史上的今天:
贊
0
賞

