Pyplot绘制Y轴顺序混乱问题求助
解决Matplotlib Pyplot Y轴顺序混乱问题
嘿,我一眼就瞅出你这个Y轴顺序混乱的问题大概率出在哪了——你存储温度数据的时候没把字符串转成数值类型!Matplotlib遇到字符串类型的数据,会默认按字典序排列,而不是我们想要的数值大小顺序,这就导致Y轴看起来乱哄哄的。
先看看你代码里的问题点:
for forecast in forecast: forecasthigh = forecast.high forecastlow = forecast.low # 这里的forecast.high和forecast.low是字符串格式,比如"28"、"15" highTemp.append(forecasthigh) lowTemp.append(forecastlow)
直接把字符串塞进列表,Matplotlib绘图时就会按字符排序,比如"10"会排在"2"后面,完全不符合温度的逻辑。
修复步骤很简单,只需两步:
- 把获取到的高温、低温数据转换成整数(或浮点数,如果有小数温度的话)
- 确保绘图时用的是数值类型的列表
修改后的完整代码(包含绘图部分):
from weather import Weather import matplotlib.pyplot as plt weather = Weather() highTemp = [] lowTemp = [] dates = [] # 新增存储日期的列表,用来做X轴 city = input('Enter the city for weather forecast \n: ') location = weather.lookup_by_location(city) condition = location.condition print("The weather forecast for",city,"is",condition.text) forecast_list = location.forecast # 避免变量名重复,把forecast改成forecast_list for forecast in forecast_list: # 关键:把字符串转成整数 forecasthigh = int(forecast.high) forecastlow = int(forecast.low) highTemp.append(forecasthigh) lowTemp.append(forecastlow) dates.append(forecast.date) # 收集日期 # 开始绘图 plt.figure(figsize=(10,6)) plt.plot(dates, highTemp, label='High Temp', marker='o') plt.plot(dates, lowTemp, label='Low Temp', marker='s') plt.xlabel('Date') plt.ylabel('Temperature') plt.title(f"Weather Forecast for {city}") plt.legend() plt.xticks(rotation=45) # 旋转日期标签,避免重叠 plt.tight_layout() # 自动调整布局 plt.show()
为什么这样改?
- 当温度数据是整数/浮点数类型时,Matplotlib会自动按数值大小对Y轴进行排序,完全符合我们的预期
- 新增的
dates列表用来对应X轴的日期,让图表更清晰 - 额外加了一些绘图优化(比如旋转标签、调整布局),让图表可读性更好
你运行修改后的代码试试,Y轴的顺序应该就正常啦!
内容的提问来源于stack exchange,提问作者Escola de Inventor
相关产品推荐
相关产品推荐

