将年积日(dayofyear)转换为圆形坐标时出现跨年异常如何解决
问题原因
角度换算逻辑倒置导致年积日对应角度计算错误。原代码中angle_by_day = 365.25/360的计算逻辑错误,全年365.25天对应完整360度圆周,正确的单日对应角度应为360 / 365.25度/天。原计算方式下全年累计转动角度仅约370度,年末和年初的坐标点存在约10度的偏差,因此无法形成闭合的圆形分布。
修正后代码
import math as m import datetime import numpy as np import matplotlib.pyplot as plt # X 为已加载的pandas dataframe # 修正角度换算逻辑:360度对应全年天数 angle_by_day = 360 / 365.25 radius = 1 # x、y取值范围为-1到1 rad_convert = m.pi/180 X['day_circle_x'] = radius * np.cos(angle_by_day * X['dayofyear'] * rad_convert) X['day_circle_y'] = radius * np.sin(angle_by_day * X['dayofyear'] * rad_convert) plt.plot(X['day_circle_x'], X['day_circle_y']) plt.axis('equal') # 避免坐标轴比例压缩导致图形显示为椭圆 plt.show()
优化建议
如果需要适配闰年的精确计算,可以动态获取当年的实际天数作为分母替换固定值365.25:
# 示例:获取某一年的实际天数 year = 2024 days_of_year = 366 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else 365 angle_by_day = 360 / days_of_year
内容的提问来源于stack exchange,提问作者Jonathan Roy
相关产品推荐
相关产品推荐

