import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateLocator, DateFormatter
from datetime import datetime, timedelta
plt.rcParams['font.family'] = 'Times New Roman'
df = pd.read_csv(r'自己csv文件', parse_dates=['date'])
fig, ax = plt.subplots(figsize=(16,9))
ax.plot_date(df.date, df.R2, fmt='b.')
ax2 = ax.twinx()
ax2.plot_date(df.date, df.MAE, fmt='r.')
ax2.spines['left'].set_color('blue')
ax2.spines['right'].set_color('red')
plt.xticks(rotation=90, ha='center')
# 左侧y轴的刻度线标签颜色
ax.tick_params(axis='y', colors='b')
# 右侧y轴的刻度线标签颜色
ax2.tick_params(axis='y', colors='r')
date_locator = AutoDateLocator()
ax.xaxis.set_major_locator(date_locator)
date_formatter = DateFormatter('%Y')
ax.xaxis.set_major_formatter(date_formatter)
ax.set_xlabel('time')
ax.set_ylabel('Cross validation R2',c='b')
ax2.set_ylabel('MAE(μg/m3)',c='r')
# 在每个年份的x轴加上竖直线,不要标签,要标签的话自己取消注释
for year in range(2015, 2022):
ax.axvline(datetime(year, 1, 1), c='k', lw=0.5, ls='--')
# ax.text(datetime(year, 1, 1), 0.1, str(year), c='k', ha='center', va='bottom', rotation=90, fontsize=12)
ax.scatter(df.date, df.R2, c=df.R2, cmap='YlOrRd', s=20)
ax2.scatter(df.date, df.MAE, c=df.MAE, cmap='YlGnBu', s=20)
plt.subplots_adjust(top=0.8, bottom=0.2, left=0.15, right=0.85)
plt.show()
# 保存图片
fig.savefig(r'输出位置', dpi=1000, bbox_inches='tight')
此为结果图: