如何使xticks在matplotlib绘图上具有每月间隔而不是每天间隔

2024-06-07 10:26:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,索引为datetime。 有重复的索引。这里是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一起使用set_major_locator,但结果没有显示任何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月中旬

编辑: 将Date列转换为datetime后,新图形的外观如下所示。如果我使用set_major_locator/formatter,则点位于右侧,但XTICK将重置为每天并重叠

enter image description here


Tags: datetypechartaxtotalsetlocatortrip
1条回答
网友
1楼 · 发布于 2024-06-07 10:26:06

您的代码是正确的:

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]])

相关问题 更多 >

    热门问题