如何在python中绘制非连续的自定义日期格式

2024-10-03 06:28:54 发布

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

我有一个自定义日期格式的列:YYYYWeekNo例如201801201802…201851201852

当我有从201752跳到201801的数据时,问题就出现了,这创建了一个图,将数据视为100比例的连续数据,因此图形是扭曲的

有没有办法用非连续的x标签来解析这个图?你知道吗

x = []
year = 2017
for i in range(104):
    j = i+1
    if j <= 52:
        x.append(year * 100 + j)
    else:
        k = j - 52
        x.append(((year+1) * 100 ) + k)


np.random.seed(1)
values = np.random.randint(low=0, high=5000, size=104)


df = pd.DataFrame.from_dict({'year_week': x, 'values': values})
df.set_index('year_week').plot(figsize=(15, 5))

enter image description here


Tags: 数据图形dffor格式nprandom标签
1条回答
网友
1楼 · 发布于 2024-10-03 06:28:54

可以使用matplotlib example来“打断”轴。这将是定制版本:

import matplotlib.pylab as plt
import numpy as np

x = []
year = 2017
for i in range(104):
    j = i+1
    if j <= 52:
        x.append(year * 100 + j)
    else:
        k = j - 52
        x.append(((year+1) * 100 ) + k)
np.random.seed(1)
values = np.random.randint(low=0, high=5000, size=104)

df = pd.DataFrame.from_dict({'year_week': x, 'values': values})

f,(ax,ax2) = plt.subplots(1,2,sharey=True, facecolor='w', figsize=(10,10))

# plot the same data on both axes
ax.plot(df['year_week'], df['values'])
ax2.plot(df['year_week'], df['values'])

ax.set_xlim(201700,201753)
ax2.set_xlim(201800,201853)

# hide the spines between ax and ax2
ax.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax.yaxis.tick_left()
ax.tick_params()
ax2.yaxis.tick_right()

#this gets rid of scientific notation, so it's more readable
ax.ticklabel_format(useOffset=False)
ax2.ticklabel_format(useOffset=False)
plt.show()

输出:

enter image description here

更重要的是,似乎有一个专门解决这个问题的软件包:

Brokenaxes

相关问题 更多 >