什么可能导致 Matplotlib 忽略 y 轴刻度定位器?

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

我有一个包含两列的表格:开始日期和停止日期。我以这两个日期之间的小时间隔创建一系列日期时间值,从开始日期的 00:00 开始,到结束日期的 23:00 结束。

这很有用,因为我有第二个表,其中包含每小时的数据以及相应的时间戳,包括拍摄的日期和小时。

我的代码迭代第一个表的每一行,将日期范围内的所有日期与数据表中各自的值进行匹配。然后我将它们一一绘制在它们自己的子图中。如果时间范围不在数据表内,我就全零。

当我尝试为每个子图设置 y 轴的限制和刻度线时,出现了问题。我特意指定希望 y 限制介于 -150 和 150 之间,并以 50 为间隔设置刻度线。但是,当我绘制此图时,我会得到具有不同间距的随机值。例如,在一张图表上,我在 15 处得到一个刻度,在 27 处得到另一个刻度。在下一张图表中,我在 -12 处得到一个刻度,在 -37 处得到另一个刻度 但是出了问题:-37 刻度高于 -12 刻度!

我的代码如下:

fig, axs = plt.subplots(len(themis_data), figsize=(10, 2*len(themis_data)))
for ax, (index, row) in zip(axs, themis_data.iterrows()):
    # Create a series of timestamps at a 1-hour cadence between the start and stop times
    date_range = pd.date_range(start=row['Date_Start'], end=row['Date_Stop']+pd.Timedelta(days=1)-pd.Timedelta(seconds=1), freq='1h')
    # Return all the values that correspond to these timestamps
    filtered_dst_values = DST_filtered.loc[DST_filtered['Date'].isin(date_range), 'DST']

    #For some reason, if there is no data then fill all 0
    if len(filtered_dst_values) == 0:
        filtered_dst_values = pd.Series([0] * len(date_range))

    # Plot the returned values
    ax.plot(date_range, filtered_dst_values)

    #Format the axis: set the limits, tick locators, and format for the labels on the x-axis
    ax.set_ylim((-150, 150))
    ax.yaxis.set_major_locator(MultipleLocator(50))
    ax.xaxis.set_major_locator(mdates.DayLocator(interval=2))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))

plt.tight_layout()
plt.show()

看起来像一个简单的绘图例程,但输出如下所示:

python pandas matplotlib datetime
1个回答
0
投票

您遇到的问题似乎与子图 y 轴上的刻度位置和间距有关。让我们通过单独调整每个子图的 y 轴限制和刻度定位器来解决这个问题。

您当前正在为循环中的每个子图设置 y 轴限制和刻度定位器并对其进行迭代。但是,子图之间的数据范围和值可能会有所不同,这可能会导致意外的刻度位置和间距。

以下是如何修改代码以确保每个子图的 y 轴限制和刻度定位器一致:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import MultipleLocator

fig, axs = plt.subplots(len(themis_data), figsize=(10, 2*len(themis_data)))

for ax, (index, row) in zip(axs, themis_data.iterrows()):
    date_range = pd.date_range(start=row['Date_Start'], end=row['Date_Stop']+pd.Timedelta(days=1)-pd.Timedelta(seconds=1), freq='1h')
    filtered_dst_values = DST_filtered.loc[DST_filtered['Date'].isin(date_range), 'DST']

    if len(filtered_dst_values) == 0:
        filtered_dst_values = pd.Series([0] * len(date_range))

    ax.plot(date_range, filtered_dst_values)

    # Set y-axis limits and tick locators
    ax.set_ylim((-150, 150))
    ax.yaxis.set_major_locator(MultipleLocator(50))

    # Format x-axis labels
    ax.xaxis.set_major_locator(mdates.DayLocator(interval=2))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))

plt.tight_layout()
plt.show()

通过此修改,每个子图的 y 轴限制和刻度定位器将保持一致,确保刻度在所有子图上均匀分布并正确对齐。这应该可以解决您遇到的不规则刻度间距和定位问题。

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