防止 matplotlib 连接具有缺失值的不相关数据点图

问题描述 投票:0回答:1

我有代表一天中某个区域温度的数据集。我有几个月的数据,但由于硬件原因,其中一些数据丢失了。数据可能会丢失几个小时,甚至一次丢失几个小时。

因此,我必须将 NaN 值添加到我的数据集中,以便更好地表示它们。我已经填充了一天中几个小时的缺失数据,但没有填充几天的空数据。

我想使用曲线将温度值显示为时间的函数以及整个月的数据。

我想只显示非空数据,而不让 matplotlib 链接不相关的数据。

Data for October 2023

问题在于,在此示例中,即使有几天的数据丢失,某些数据已链接,而其他数据则未链接。 我们可以看到 2023/10/09 左右的数据已链接,而在 2023/10/21 至 2023/10/29 之间,尽管有相当多的缺失数据,但数据并未链接。

为了解决这个问题,我已经尝试过每天显示数据以避免 matplotlib 将数据链接在一起,但不幸的是,通过这个解决方案,我最终得到了与数天数据一样多的图例。 这是给我上述结果的代码:

"""
Create and display the temperature distribution plot (curves) for a given month.

Parameters:
month_year_data (pandas.DataFrame): DataFrame containing hourly temperature data for the month.
month_name (str): Name of the month for labeling the plot.
year (int): Year for labeling the plot.

Returns:
None
"""
# Create a single figure
fig, ax = plt.subplots(figsize=(20, 10))

# Plot temperature distribution for each zone
zones = ['Far range', 'Mid range', 'Near range']
colors = ['blue', 'green', 'red', 'black']  # Define colors for each zone
for i, zone in enumerate(zones):
    ax.plot(month_year_data.index, month_year_data[zone], label=zone, color=colors[i], linestyle='-')

# Set labels for x and y axes
ax.set_xlabel('Time')
ax.set_ylabel('Temperature (°C)')
# Set title for the plot
ax.set_title(f'Temperature as a function of time by Hour - {month_name}-{year}')
# Rotate x-axis labels for better readability
plt.xticks(rotation=45)
# Add legend
ax.legend()
python dataframe matplotlib missing-data curve
1个回答
0
投票

我已经填写了一天中几个小时的缺失数据,但没有填写几天的空数据。

如果中间没有

NaN

,Matplotlib 将链接连续的点,无论这些点对应的实际时间差如何。我建议您将整个间隔分成等间隔的小时,并用您拥有的数据填充数组,并用 
NaN
 填充缺失的数据。例如,如果没有特定日期的条目,您可能需要向数据帧添加行。您可能想看看
这个答案这个答案

我看到您的数据已按日期/时间编入索引。尝试:

rng = pd.date_range(month_year_data.index.min(), month_year_data.index.max(), freq='H') month_year_data_filled = month_year_data.reindex(rng)
缺失值应自动填充

NaN

,因为它是默认值。

© www.soinside.com 2019 - 2024. All rights reserved.