gpt4 book ai didi

python - 我怎样才能让 xticks 在我的 matplotlib 图上有一个每月的间隔而不是每天

转载 作者:行者123 更新时间:2023-12-05 05:00:01 25 4
gpt4 key购买 nike

我有一个索引为日期时间的数据框。有重复的索引。这是 df.head()

                  Landing         Date           Boat    Trip Type  Anglers ... Albacore    Barracuda   Total Caught
Date
2020-01-01 daveys-locker 2020-01-01 Freelance 3/4 Day 55 ... 0 0 223
2020-01-01 daveys-locker 2020-01-01 Western Pride 1/2 Day PM 38 ... 0 0 137
2020-01-02 daveys-locker 2020-01-02 Freelance 3/4 Day 75 ... 0 0 185
2020-01-02 daveys-locker 2020-01-02 Western Pride 1/2 Day PM 38 ... 0 0 144
2020-01-03 daveys-locker 2020-01-03 Freelance 3/4 Day 77 ... 0 0 395

我已经尝试了几种方法来让 xticks 不显示在每一天或每个索引(甚至无法分辨,因为有太多)。这是我的原件。

fig, ax = plt.subplots(figsize=(40,25))
chart = sbn.scatterplot(x='Date',y='Total Caught',data=daveysdf_2019, hue='Boat', style='Trip Type',s=150)
ax.set_title('Daveys Locker 2019 Totals')
ax.legend(framealpha=0.5)
chart.set_xticklabels(labels=daveysdf_2019.Date.unique(),rotation=75)
figure = chart.get_figure()

enter image description here

我尝试将 set_major_locatormatplotlib.dates.MonthLocatorformatter 一起使用,但最终没有显示任何 xticks

from matplotlib.dates import MonthLocator, DateFormatter
fig, ax = plt.subplots(figsize=(40,25))
chart = sbn.scatterplot(x='Date',y='Total Caught',data=daveysdf_2019, hue='Boat', style='Trip Type',s=150)
ax.set_title('Daveys Locker 2019 Totals')
ax.legend(framealpha=0.5)
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m'))
chart.set_xticklabels(labels=daveysdf_2019.Date.unique(),rotation=75)

enter image description here

我还尝试了一些我不记得的其他方法,它使 xtick 间隔间隔开,但仅限于从第一个日期到 2 月中旬。

编辑:将日期列转换为日期时间后,新图形如下所示。如果我使用 set_major_locator/formatter,这些点在右边,但 xticks 会重置为每天并重叠。

enter image description here

最佳答案

你的代码是正确的:

from matplotlib.dates import MonthLocator, DateFormatter
fig, ax = plt.subplots(figsize=(40,25))
chart = sbn.scatterplot(x='Date',y='Total Caught',data=daveysdf_2019, hue='Boat', style='Trip Type',s=150)
ax.set_title('Daveys Locker 2019 Totals')
ax.legend(framealpha=0.5)
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m'))
chart.set_xticklabels(labels=daveysdf_2019.Date.unique(),rotation=75)

但是你需要在这段代码的末尾添加一行以避免matplotlib不显示任何刻度,你需要设置轴的xlim:

ax.set_xlim([daveysdf_2019['Date'].iloc[0], daveysdf_2019['Date'].iloc[-1]])

关于python - 我怎样才能让 xticks 在我的 matplotlib 图上有一个每月的间隔而不是每天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63323424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com