Bootstrap

python生成年际变化图:以生成包含3个年际变化图子图为例

# -*- coding: utf-8 -*-
"""
生成3种模型的年际变化图,其余1种模型以点的形式添加到图上
YMJ 20230515 21:32
"""
import datetime
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, AutoDateLocator
from sklearn.linear_model import LinearRegression
import seaborn as sns
from matplotlib.pyplot import MultipleLocator
import pylab
from pylab import mpl
from datetime import datetime
import matplotlib.dates as mdates
import datetime, time
 
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
 
dir1 = 'D:\\YMJ_file\\通量数据相关\\All模型评价\\图3\\PTJPL'
dir2= 'D:\\YMJ_file\\通量数据相关\\All模型评价\\图3\\SGCF'
dir3 = 'D:\\YMJ_file\\通量数据相关\\All模型评价\\图3\\METRIC'
 
Sites_Name = ["AR", "CBS", "CL", "DM", "DHS", \
              "HBS", "HZZ", "MY", "QYZ", "SDQ"]
 
# 遍历文件夹下的文件,每个站点生成一个包含3个子图的大图
file_list1 = []
for root, subroot, files in os.walk(dir1):
    for file in files:
        if file.endswith(".xlsx"):
            file_path = os.path.join(root, file)
            file_list1.append(file_path)
print(file_list1)
 
file_list2 = []
for root, subroot, files in os.walk(dir2):
    for file in files:
        if file.endswith(".xlsx"):
            file_path = os.path.join(root, file)
            file_list2.append(file_path)
print(file_list2)
 
file_list3 = []
for root, subroot, files in os.walk(dir3):
    for file in files:
        if file.endswith(".xlsx"):
            file_path = os.path.join(root, file)
            file_list3.append(file_path)
print(file_list3)
 
 
for i in range(len(file_list1)):
    print(file_list1[i])
    print(file_list2[i])
    print(file_list3[i])
 
    df1 = pd.read_excel(file_list1[i])
    df2 = pd.read_excel(file_list2[i])
    df3 = pd.read_excel(file_list3[i])
 
    # 合并所有文件
    if len(df1) < len(df2):
        df = pd.merge(df1, df2, how="left", on=['time'])
    else:
        df = pd.merge(df1, df2, how="right", on=['time'])
 
    if len(df) < len(df3):
        df = pd.merge(df, df3, how="left", on=['time'])
    else:
        df = pd.merge(df, df3, how="right", on=['time'])
 
    df = pd.DataFrame(df)
    # 将METRIC模型的结果也合并过来,并对缺失值填充-6999
    df = pd.merge(df, df4, how="left", on=['time']).fillna(-6999)
 
    y1 = df["LE_daytime"]
    y2 = df["E_daytime1"]
    y3 = df["E_daytime2"]
    y4 = df["E_daytime3"]
 
 
    fig = plt.figure(dpi=300)
    # 布局,3行,1列,上下之间的间隙为0
    gs = fig.add_gridspec(3, 1, hspace=0)
    axs = gs.subplots(sharex=True, sharey=True)  # 共享x轴和y轴的刻度和标签
    # 一个大的标题
    site_name = Sites_Name[i]
    fig.suptitle(site_name, x=0.5, y=0.92, fontsize=20)
    axs[0].plot(y1, "-", color=(38/255, 70/255, 83/255), label="EC measurements")
    axs[0].set_ylim(-50, 550)
    axs[1].plot(y2, "-", color=(42/255, 157/255, 142/255), label="PTJPL")
    axs[3].plot(y3, "-", color=(243/255, 162/255, 97/255), label="SGCF")
    # 将点画进去
    axs[0].plot(y4, 'v', color=(230/255, 111/255, 81/255), label='METRIC', markersize=7)
 
    # 为了去掉时间缺失的部分,上部去掉x,下部使用全局xticks
    x = df["time"]
    x_ = []
    for j in range(0, len(x), 183):
        str_time = (x[j] + datetime.timedelta(days=1)).strftime("%Y/%m/%d")
        x_.append(str_time)
    plt.xticks(np.arange(0, len(x), step=183), x_, rotation=30)  # rotation=90
    fig.text(0.06, 0.5, 'LE(W/$\mathdefault{m^2}$)', va='center', rotation='vertical', fontsize=16)
    fig.legend(ncol=6, loc="lower center")  # 生成全局的图例
    fig.subplots_adjust(bottom=0.16)
    # fig.legend(ncol=4, bbox_to_anchor = (0.75, 0.07)) # 放置全局图例的另一种方式
 
    outpath = os.path.join(file_list1[i].split("PTJPL")[0] + Sites_Name[i] + ".tiff")
    plt.savefig(outpath, bbox_inches='tight')  # tight设置是让图片裁剪的刚刚好

;