【杂糅子图】

# -*- coding: utf-8 -*-
"""
Created on Sun Oct 23 13:57:22 2022

@author: Lenovo
"""

import seaborn as sns
from scipy.stats import pearsonr
import matplotlib as mpl
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
from mpl_toolkits.axes_grid1 import make_axes_locatable

plt.rcParams['savefig.dpi'] = 600 #图片像素
plt.rcParams['figure.dpi'] = 600

path = r'D:\河北省土地利用\19901'
for i ,year in zip(os.listdir(path),[1990,1999,2004,2009,2014,2019]):
    
    p = pd.read_csv(os.path.join(path,i))
    print(p.columns)
    p = p[['MEAN','MEAN_1','MEAN_12', 'MEAN_12_13']]
    
    p0 = p.loc[p['MEAN_1']>=0,['MEAN','MEAN_1']]
    p0['MEAN']=[x/100-273 for x in p0['MEAN']]
    p0 = p0.reset_index(drop=True)
    
    p1 = p.loc[p['MEAN_12']>=0,['MEAN','MEAN_12']]
    p1['MEAN']=[x/100-273 for x in p1['MEAN']]
    p1 = p1.reset_index(drop=True)
    
    p2 = p.loc[p['MEAN_12_13']>=0,['MEAN','MEAN_12_13']]
    p2['MEAN']=[x/100-273 for x in p2['MEAN']]
    p2 = p2.reset_index(drop=True)
    
    x = p0['MEAN_1']
    y = p0['MEAN']
    
    
    x1 = p1['MEAN_12']
    y1 = p1['MEAN']
    
    x2 = p2['MEAN_12_13']
    y2 = p2['MEAN']
    
    
    plt.figure(figsize=(20,5))
    label_variable=['nothin',"PS","LS","ES"]
    for num,x,y ,name in zip([1,2,3,4],[x,x1,x2,0],[y,y1,y2,0],['PS','LS','ES',0]):

        if num <=3:
                
            #计算点密度
            xy = 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=(6,5),dpi=500) #figuresize图片比例
            
            fw=int(max(x))
            fw_min=int(min(x))
            
            fw1=int(max(y))+6
            fw1_min=int(min(y))-2
            plt.xlim(fw_min,fw)
            plt.ylim(5,40)
            
            # 绘图
            ax1 = plt.subplot(1,4,num)
            scatter = ax1.scatter(x,y,marker='o',c=z,s=15,label=label_variable[num],cmap='PuBuGn_r') # o是实心圆,c=是设置点的颜色,cmap设置色彩范围,'Spectral_r'和'Spectral'色彩映射相反
            divider = make_axes_locatable(ax1) #画色域图
            # plt.plot([fw_min,fw], [fw1_min,fw1], 'gray',ls='--', lw=0.8)  # 画的1:1线,线的颜色为black,线宽为0.8
            plt.scatter(x, y, c=z, s=7, cmap='jet')
            # plt.legend(frameon=False,fontsize=23,loc='upper left',markerscale=0.00001,handletextpad=0.00000000001)
            plt.axis([fw_min, fw, 5,40])  # 设置线的范围
            plt.text(15, 36, name, family = 'Times New Roman',size=23)
            z = np.polyfit(x, y, 1)
            t = np.poly1d(z)
            plt.plot(x,t(x),c='red',ls=':',lw=4.5)
            
            plt.title(year,family = 'Times New Roman',size=21)
            plt.xlabel('PLAND (%)',family = 'Times New Roman',size=22)
            plt.ylabel('LST (℃)',family = 'Times New Roman',size=22)
            plt.xticks(fontproperties='Times New Roman',size=21)
            plt.yticks(fontproperties='Times New Roman',size=21)
            
      
            
            plt.tight_layout()#让子图自动条件相互间距!
        
        if num==4:
            
            
            # print(df.columns)
            p = p[['MEAN','MEAN_1','MEAN_12', 'MEAN_12_13']]

            p.loc[p['MEAN_1']<=0] = np.nan
            # print(p['MEAN_1'])
            p.loc[p['MEAN_12']<=0] = np.nan
            p.loc[p['MEAN_12_13']<=0] = np.nan
            
            
            # def cm2inch(x,y):
            #     return x/2.54,y/2.54
            
            size1 = 21
            mpl.rcParams.update(
            {
            'text.usetex': False,
            'font.family': 'stixgeneral',
            'mathtext.fontset': 'stix',
            "font.family":'serif',
            "font.size": size1,
            "font.serif": ['Times New Roman'],
            }
            )
            fontdict = {'weight': 'bold','size':size1,'family':'SimHei'}
            
            p['LST'] = p['MEAN']
            p['PS'] = p['MEAN_1']
            p['LS'] = p['MEAN_12']
            p['ES'] = p['MEAN_12_13']
            p = p[['LST','PS','LS','ES']]
            p666 = p.copy()
            df_coor=p.corr()
            
            print(df_coor)
            ax1 = plt.subplot(1,4,num)
            ax1 = plt.gca()
            
            #构造mask,去除重复数据显示
            mask = np.zeros_like(df_coor)
            mask[np.triu_indices_from(mask)] = True
            mask2 = mask
            mask = (np.flipud(mask)-1)*(-1)
            mask = np.rot90(mask,k = -1)
            
            im1 = sns.heatmap(df_coor,annot=True,cmap='YlGnBu'
            , mask=mask#构造mask,去除重复数据显示twilight_shifted_r coolwarm_r seismic_r Blues
            ,vmax=1,vmin=-1
            , fmt='.2f',ax = ax1
            ,annot_kws={"fontsize":20})
            
            plt.title(year,family = 'Times New Roman',size=21)
            plt.xticks(fontsize=20)
            plt.yticks(fontsize=20)
            cbar = ax1.collections[0].colorbar
            # ax1 = sns.heatmap(df.corr(), annot=True, cmap='YlGnBu', annot_kws={"fontsize":20})
            cbar.ax.tick_params(labelsize=20)
            ax1.tick_params(axis = 'both', length=0)
            
            #计算相关性显著性并显示
            rlist = []
            plist = []
            for i in p666.columns.values:
                print(i)
                for k in p666.columns.values:
                    # print(j)
                    r,pa = pearsonr(df_coor[i],df_coor[k])
                    # print(r)
                    rlist.append(r)
                    plist.append(pa)
            
            rarr = np.asarray(rlist).reshape(len(p.columns.values),len(p.columns.values))
            parr = np.asarray(plist).reshape(len(p.columns.values),len(p.columns.values))
            xlist = ax1.get_xticks()
            ylist = ax1.get_yticks()
            
            widthx = 0
            widthy = -0.15
            
            for m in ax1.get_xticks():
                for n in ax1.get_yticks():
                    pv = (parr[int(m),int(n)])
                    print(pv)
                    rv = (rarr[int(m),int(n)])
                    print(rv)
                    if mask2[int(m),int(n)]<1.:
                        if abs(rv) > 0.5:
                            
                            if  pv> 0:
                                ax1.text(n+widthx,m+widthy,'**',ha = 'center',color = 'black')
                            if  pv< -0.1:
                                ax1.text(n+widthx,m+widthy,'**',ha = 'center',color = 'black')
                            if  pv< 0.001:
                                print([int(m),int(n)])
                                ax1.text(n+widthx,m+widthy,'***',ha = 'center',color = 'black')
                        else: 
                            if  pv< 0.05 and pv>= 0.01:
                                ax1.text(n+widthx,m+widthy,'*',ha = 'center',color = 'black')
                            elif  pv> 0.01:
                                ax1.text(n+widthx,m+widthy,'**',ha = 'center',color = 'black')
                            elif  pv< 0.001:
                                ax1.text(n+widthx,m+widthy,'***',ha = 'center',color = 'black')
    plt.savefig(os.path.join(r'C:\Users\Lenovo\Desktop\BOXPLOT\SCATTER','year')
                        , bbox_inches='tight')
    plt.show()
                
            
            
            
            
            
        
        
        
        
        # label_variable=["PS","ES","LS"]
        # color_list=['tab:blue','tab:orange','tab:green','red']
        # font1 = {'family' : 'Arial',
        #          'weight' : 'normal',
        #          'size'   : 12,
        #         }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值