Python绘图(曲线,柱状图)

一、曲线图

曲线图示例:

Excel数据实例:

代码:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random

# 设置线粗细
lw = 1
# 调整刻度字体大小
k = 12
# 调整标题字体大小
t = 12

#设置标题大小
fontsize1 = 20
# 将全局字体调为'Times New Roman'
plt.rcParams['font.family'] = 'Times New Roman'

#读取Excel文件
dataset = pd.read_excel('PV_DATA_1.xlsx')


label = dataset.iloc[:, 0].values                             #Excel表格第 0 列
predicted_Time2Vec_WDCNN_BiLSTM = dataset.iloc[:, 1].values   #Excel表格第 1 列
predicted_LSTMfoemer = dataset.iloc[:, 2].values              #Excel表格第 2 列                
predicted_IEDN_RNET = dataset.iloc[:, 3].values               #Excel表格第 3 列     
predicted_NWP_Time2Vec_xLSTM_CCNN = dataset.iloc[:, 4].values #Excel表格第 4 列     

# 指定图片尺寸 分辨率
fig = plt.figure(figsize=(10, 3), dpi=1000)
plt.grid(linestyle=":", color="#7b7879") #控制虚线,去掉后改变a b 控制绘图大小,截图后制作放大图

#绘制第a行到第b行的数据
a = 0
b = 100

#  c 兰    #589E40  绿    #F9AB0E  黄    #c74c25 红

# 画图
plt.plot(label[a:b], "#3C36D9", label="Actual value", linestyle='--', linewidth=lw)
plt.plot(predicted_Time2Vec_WDCNN_BiLSTM[a:b], "#F9AB0E", label="Time2Vec-\nWDCNN-BiLSTM", linewidth=lw) # 1
plt.plot(predicted_LSTMfoemer[a:b], "#589E40", label="LSTMfoemer", linewidth=lw)                         # 2
plt.plot(predicted_IEDN_RNET[a:b], "#c74c25", label="IEDN-RNET", linewidth=lw)                           # 3
plt.plot(predicted_NWP_Time2Vec_xLSTM_CCNN[a:b], "c", label="NWP-Time2Vec-\nxLSTM-CCNN", linewidth=lw)   # 4

plt.xlabel("Test sample (1h/step)", fontsize=t)
plt.ylabel("Power (MW)", fontsize=t)

# 调整刻度字体大小
plt.xticks(fontsize=k)
plt.yticks(fontsize=k)
# 添加标题和标签
plt.title("Case 2: Photovoltaic power forecast comparison (1 Day)")#添加标题
# 设置 y 轴的刻度范围
plt.ylim(0, 1300)  # 这里可以根据实际数据的范围调整

plt.show()

单独绘制图例:

代码:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines
plt.rcParams['font.family'] = 'Times New Roman'
# 定义颜色列表和标签
colors = ["#3C36D9", "c", "#589E40", "#F9AB0E", "#c74c25"]
labels = ['A', "B", 'C', 'D', 'E']

# 创建一个图形
plt.figure(figsize=(8, 4),dpi=1000)

# 创建图例项,'Actual value' 设为虚线,其余为实线
handles = []
for label, color in zip(labels, colors):
    if label == 'Actual value':
        # 为 'Actual value' 设置虚线
        handle = mlines.Line2D([], [], color=color, label=label, lw=3, linestyle='--')
    else:
        # 其余项设置为实线
        handle = mlines.Line2D([], [], color=color, label=label, lw=3)
    handles.append(handle)

# 添加图例,并设置每行显示 5 个图例项
plt.legend(handles=handles, loc='center', fontsize=12, ncol=5)

# 设置图形的一些参数
plt.axis('off')  # 不绘制坐标轴

# 显示图例
plt.show()

二、柱状图

示例:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

# 设置全局字体为Times New Roman
plt.rcParams['font.family'] = 'Times New Roman'


xytext = 1  #设置柱状图数值与柱状图距离
dpi = 500 #设置分辨率
fontsize1 = 20 #设置标题字体大小
fontsize2 = 15 #设置x y轴标题字体大小
fontsize3 = 15 #设置刻度字体大小
fontsize_num = 12  # 设置柱状图上数值的字体大小





# 每个评价指标(MAE, MSE, RMSE, R2)对应6个模型的值
data = {
    'Model': ['LSTM-CNN', 'LSTM-CCNN', 'xLSTM-CNN', 'xLSTM-CCNN', 'Time2Vec-xLSTM-CCNN', 'NWP-Time2Vec-xLSTM-CCNN'],
    'MAE': [32.08,26.15,25.34,15.69,13.30,10.57 ],
    'MSE': [1531.44,829.24,734.06,299.28,254.01,168.91],
    'RMSE': [39.13,28.80,27.09,17.30,15.94,13.00 ],
    '$R^2$': [0.801,0.899,0.918,0.951,0.961,0.981]
}

# 转换为DataFrame
df = pd.DataFrame(data)

# 将DataFrame转换为长格式,以便绘制柱状图
df_long = pd.melt(df, id_vars=['Model'], var_name='Metric', value_name='Value')

# 创建一个大的图形
fig, ax1 = plt.subplots(figsize=(16, 6), dpi = dpi)


# 定义颜色列表
colors_mae = ['#4E687C', '#B2E8E8', '#8FB9AB', '#F4D096', '#F08976', '#F7CECA']  # 为MAE定义6种颜色
colors_mse = ['#4E687C', '#B2E8E8', '#8FB9AB', '#F4D096', '#F08976', '#F7CECA']    # 为MSE定义不同颜色
colors_rmse =['#4E687C', '#B2E8E8', '#8FB9AB', '#F4D096', '#F08976', '#F7CECA']      # 为RMSE定义不同颜色
colors_r2 = ['#4E687C', '#B2E8E8', '#8FB9AB', '#F4D096', '#F08976', '#F7CECA']      # 为R2定义不同颜色

# 绘制MAE的柱状图(第一个y轴),使用指定的颜色
ax1 = sns.barplot(x='Metric', y='Value', hue='Model', data=df_long[df_long['Metric'] == 'MAE'], ax=ax1, palette=colors_mae, legend=False)

# 在柱状图上添加数值标签
for p in ax1.patches:
    ax1.annotate(f'{p.get_height():.2f}', 
                 (p.get_x() + p.get_width() / 2., p.get_height()), 
                 xytext=(0, xytext), 
                 textcoords='offset points', 
                 ha='center', va='bottom', fontsize=fontsize_num, color='black')

# 创建第二个y轴用于MSE(使用twinx())
ax2 = ax1.twinx()
sns.barplot(x='Metric', y='Value', hue='Model', data=df_long[df_long['Metric'] == 'MSE'], ax=ax2, palette=colors_mse, legend=False)

# 在MSE柱状图上添加数值标签
for p in ax2.patches:
    ax2.annotate(f'{p.get_height():.2f}', 
                 (p.get_x() + p.get_width() / 2., p.get_height()), 
                 xytext=(0, xytext), 
                 textcoords='offset points', 
                 ha='center', va='bottom', fontsize=fontsize_num, color='black')

# 创建第三个y轴用于RMSE(使用twinx())
ax3 = ax1.twinx()
sns.barplot(x='Metric', y='Value', hue='Model', data=df_long[df_long['Metric'] == 'RMSE'], ax=ax3, palette=colors_rmse, legend=False)

# 在RMSE柱状图上添加数值标签
for p in ax3.patches:
    ax3.annotate(f'{p.get_height():.2f}', 
                 (p.get_x() + p.get_width() / 2., p.get_height()), 
                 xytext=(0, xytext), 
                 textcoords='offset points', 
                 ha='center', va='bottom', fontsize=fontsize_num, color='black')

# 创建第四个y轴用于R2(使用twinx())
ax4 = ax1.twinx()
sns.barplot(x='Metric', y='Value', hue='Model', data=df_long[df_long['Metric'] == '$R^2$'], ax=ax4, palette=colors_r2, legend=False)

# 在R2柱状图上添加数值标签
for p in ax4.patches:
    ax4.annotate(f'{p.get_height():.3f}', 
                 (p.get_x() + p.get_width() / 2., p.get_height()), 
                 xytext=(0, xytext), 
                 textcoords='offset points', 
                 ha='center', va='bottom', fontsize=fontsize_num, color='black')

    # 设置R2 Y轴的坐标范围
ax4.set_ylim(0.70, 1.0)  # 设置R2的Y轴范围为0.95到1.0


# 设置标题和标签
ax1.set_title('Comparison of indicators for photovoltaic power prediction (7 Days)', fontsize=fontsize1)
ax1.set_xlabel('Metrics', fontsize=fontsize2)

# 设置每个y轴的标签
ax1.set_ylabel('MAE', fontsize=fontsize2)
ax2.set_ylabel('MSE', fontsize=fontsize2)
ax3.set_ylabel('RMSE', fontsize=fontsize2)
ax4.set_ylabel('$R^2$', fontsize=fontsize2)

# 设置刻度标签的字体大小
ax1.tick_params(axis='both', labelsize=fontsize3)
ax2.tick_params(axis='both', labelsize=fontsize3)
ax3.tick_params(axis='both', labelsize=fontsize3)
ax4.tick_params(axis='both', labelsize=fontsize3)

# 为不同的y轴调整位置(避免标签重叠)
ax2.spines['right'].set_position(('outward', 0))  # 移动第二个y轴
ax3.spines['right'].set_position(('outward', 56))  # 移动第三个y轴
ax4.spines['right'].set_position(('outward', 105))  # 移动第四个y轴

# 取消图例显示
ax1.legend().set_visible(False)


# 显示图形
plt.tight_layout()
plt.show()

三、拟合图

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import r2_score
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import pandas as pd
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
import numpy as np
# 将全局字体调为'Times New Roman'
plt.rcParams['font.family'] = 'Times New Roman'
# 读取Excel文件
df = pd.read_excel('After_Natal_PV1.xlsx')
observed = df.iloc[:, 0].values
predicted = df.iloc[:, 1].values

# 拟合直线
model = LinearRegression()
model.fit(observed.reshape(-1, 1), predicted)  # 训练模型

# 获取拟合的预测值
predicted_fit = model.predict(observed.reshape(-1, 1))
z = 14

fig = plt.figure(figsize=(8, 5), dpi=500)
# 绘制实测温度与预测温度的散点图
plt.scatter(observed, predicted, alpha=0.4,s=10,label='Data Points')
# 绘制拟合的直线
plt.plot(observed, predicted_fit, color='red',linestyle='--', label='Fit Line')
# 添加标签和标题
plt.title('NASA vs Measured Humidity', fontsize=z)
plt.xlabel('Measured Humidity (%)', fontsize=z)
plt.ylabel('NASA Humidity (%)', fontsize=z)
# 显示图例
plt.legend(fontsize=z)

# 调整刻度字体大小
plt.xticks(fontsize=z) 
plt.yticks(fontsize=z)

# 显示图形
plt.show()

# 计算指标
r2 = r2_score(observed, predicted)
mae = mean_absolute_error(observed, predicted)
mse = mean_squared_error(observed, predicted)
rmse = np.sqrt(mse)  # 或 mean_squared_error(actual, predicted, squared=False)

# 打印结果
print(f"R² (R-squared): {r2:.4f}")
print(f"MAE (Mean Absolute Error): {mae:.4f}")
print(f"MSE (Mean Squared Error): {mse:.4f}")
print(f"RMSE (Root Mean Squared Error): {rmse:.4f}")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值