PVLIB多日期单日AC功率对比绘图:X轴仅保留时间的实现求助
解决PVLIB绘制单日AC功率叠加曲线的X轴日期分散问题
问题描述
需要生成不同日期(如3月、6月、9月、12月)的单日AC输出功率叠加曲线图,要求X轴仅显示当日时间、不含日期信息,让曲线在同一时间轴上直观对比。但当前代码生成的图表中,X轴包含具体日期,导致各日期的曲线分散在不同区间,无法实现预期的对比效果。
修改方案
核心思路是统一所有曲线的X轴时间基准:将每个日期的AC功率数据的索引替换为仅保留当日时间的格式(或统一映射到同一个虚拟日期的时间戳),让Matplotlib将所有曲线对齐到同一时间轴,再设置X轴刻度仅显示时间部分。
修改后完整代码
import pvIdealModule import matplotlib.pyplot as plt from pvlib import pvsystem, modelchain, location import pandas as pd from matplotlib.dates import DateFormatter def run(beginTime, endTime): array_kwargs = dict( module_parameters=dict(pdc0=0.385, gamma_pdc=-0.004), temperature_model_parameters=dict(a=-3.47, b=-0.0594, deltaT=3) ) arrays = [ pvsystem.Array(pvsystem.FixedMount(40, 88), name='East', modules_per_string=12, **array_kwargs), pvsystem.Array(pvsystem.FixedMount(40, 268), name='West', modules_per_string=10, **array_kwargs), ] # latitude, longitude, TZ, height, name timeZone = 'Europe/Berlin' loc = location.Location(51.3, 9.5, timeZone) system = pvsystem.PVSystem(arrays=arrays, inverter_parameters=dict(pdc0=8)) mc = modelchain.ModelChain(system, loc, aoi_model='physical', spectral_model='no_loss') times = pd.date_range(beginTime, endTime, freq='5min', tz=timeZone) weather = loc.get_clearsky(times) mc.run_model(weather) return mc, system plt.rcParams['figure.figsize'] = [20, 12] fig, ax = plt.subplots() # 处理3月数据,统一X轴时间基准 mc, system = pvIdealModule.run('2022-03-21 05:00', '2022-03-21 21:30') ac_march = mc.results.ac.copy() # 将索引替换为虚拟日期的时间戳,仅保留时分秒 ac_march.index = pd.to_datetime('2020-01-01 ' + ac_march.index.strftime('%H:%M:%S')) ac_march.plot(label='March', ax=ax) # 处理6月数据 mc, system = pvIdealModule.run('2022-06-21 05:00', '2022-06-21 21:30') ac_june = mc.results.ac.copy() ac_june.index = pd.to_datetime('2020-01-01 ' + ac_june.index.strftime('%H:%M:%S')) ac_june.plot(label='June', ax=ax) # 处理9月数据 mc, system = pvIdealModule.run('2022-09-23 05:00', '2022-09-23 21:30') ac_sept = mc.results.ac.copy() ac_sept.index = pd.to_datetime('2020-01-01 ' + ac_sept.index.strftime('%H:%M:%S')) ac_sept.plot(label='September', ax=ax) # 处理12月数据 mc, system = pvIdealModule.run('2022-12-21 05:00', '2022-12-21 21:30') ac_dec = mc.results.ac.copy() ac_dec.index = pd.to_datetime('2020-01-01 ' + ac_dec.index.strftime('%H:%M:%S')) ac_dec.plot(label='December', ax=ax) # 设置X轴仅显示时间(时分) date_formatter = DateFormatter('%H:%M') ax.xaxis.set_major_formatter(date_formatter) plt.ylabel('AC Power') plt.legend() plt.show()
关键修改点说明
- 统一时间索引:将每个日期的AC数据索引转换为同一个虚拟日期(如
2020-01-01)的时间戳,确保所有曲线的X轴坐标完全对齐。 - X轴格式设置:使用
DateFormatter('%H:%M')将X轴刻度格式化为仅显示小时和分钟,隐藏冗余的日期信息。 - 复用绘图轴:所有曲线都绘制在同一个
ax对象上,确保曲线叠加显示,实现直观对比。
内容的提问来源于stack exchange,提问作者monok
相关产品推荐
相关产品推荐

