You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python绘图时Y轴混乱问题求助

问题:Python绘图时Y轴无序、范围异常

数据存储在含两列的DataFrame中,绘图时Y轴出现无序情况,无法从原点(0,0)延伸至最大值(约4),生成的图表Y轴混乱无意义。

相关代码与数据

表格处理代码

import matplotlib.pyplot as plt
datosg = pd.DataFrame()
datosg = nochetotal[["Hour", "UV Index"]]
print(datosg)

输出的数据

Hour UV Index
32709    19    3.155
32710    19    0.197
32711    19    0.158
32712    19    0.158
32713    19    0.197
...     ...      ...
33424     6    0.592
33425     6    0.592
33426     6    0.473
33427     6    0.592
33428     6    0.473

[720 rows x 2 columns]

绘图代码

x_v = datosg["Hour"]
y_v = datosg["UV Index"]
plt.figure(figsize = (20,10))

#nochetotal.plot("Hour", "UV Index", kind="scatter")
plt.plot(x_v, y_v, color = 'g', marker = 'o')
plt.xlabel('Hour')
plt.ylabel('Indice UV')
plt.title('Indice UV ')
plt.show()

问题分析与解决

核心原因

  1. UV Index列类型错误:从输出数据看,该列值虽为数字格式,但大概率被识别为字符串类型。matplotlib对字符串类型的Y轴会按字典序排序,直接导致轴刻度混乱。
  2. 数据顺序无序:Hour列的顺序是19→…→6,绘图时x轴按原始数据顺序绘制,曲线来回跳跃,进一步加剧了Y轴的视觉混乱。

解决步骤

1. 转换UV Index为数值类型

用pd.to_numeric()强制转换列类型,同时处理可能的异常值:

datosg["UV Index"] = pd.to_numeric(datosg["UV Index"], errors='coerce')
# 可选:删除转换后产生的NaN值(如果存在)
datosg = datosg.dropna(subset=["UV Index"])

2. 按Hour排序数据

让x轴小时按顺序排列,避免曲线来回跳动:

datosg = datosg.sort_values(by="Hour")

3. 手动设置Y轴范围(可选)

如果需要Y轴从0开始,添加以下代码:

plt.ylim(bottom=0)

完整修正后的绘图代码

import matplotlib.pyplot as plt
import pandas as pd

# 数据处理
datosg = nochetotal[["Hour", "UV Index"]]
# 转换数值类型并清理无效值
datosg["UV Index"] = pd.to_numeric(datosg["UV Index"], errors='coerce')
datosg = datosg.dropna(subset=["UV Index"])
# 按小时排序
datosg = datosg.sort_values(by="Hour")

# 绘图
x_v = datosg["Hour"]
y_v = datosg["UV Index"]
plt.figure(figsize=(20,10))
plt.plot(x_v, y_v, color='g', marker='o')
plt.xlabel('Hour')
plt.ylabel('Indice UV')
plt.title('Indice UV ')
# 设置Y轴从0开始
plt.ylim(bottom=0)
plt.show()

内容的提问来源于stack exchange,提问作者iTanish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:10:19