首页 > 解决方案 > 调整水平轴上的空间

问题描述

我使用这些数据创建了如下图。

date        mean_step_by_date
26/06/2020  9398.1
27/06/2020  9280.3
28/06/2020  6394.2
29/06/2020  7202.5
30/06/2020  7457.3
20/06/2020  7688.3
21/06/2020  10038
22/06/2020  5889.5
23/06/2020  6960.4
24/06/2020  9915.5
25/06/2020  5796.3
14/06/2020  8699.5
15/06/2020  9733
16/06/2020  8191.5
17/06/2020  12608.5
19/06/2020  7708
18/06/2020  9143.5
08/06/2020  5000
09/06/2020  7251
10/06/2020  3456
11/06/2020  9983
12/06/2020  4523
13/06/2020  10547

横轴是日期,显示不正确。能否请你帮忙?谢谢你。

在此处输入图像描述

更新:这些是我与 fig.autofmt_xdate 一起使用的代码,但仍然不是很好

fig, ax = plt.subplots()
ax.plot(s['steps_date'], s['mean_step_by_date'])
fig.autofmt_xdate()
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
plt.show()

在此处输入图像描述

我已经尝试过使用这些建议的代码。有一个 ValueError 表明日期不是日期时间。当我将其转换为日期并重新运行代码时。图表很奇怪。

fig, ax = plt.subplots()
ax.plot(s['steps_date'], s['mean_step_by_date'])
locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
plt.show()

在此处输入图像描述

我还尝试了另一个类似帖子的代码,但没有显示图表

_ = plt.plot(s['steps_date'], s['mean_step_by_date'])
ax = plt.gca()
plt.axis([0,24,0,50])
plt.xticks(rotation=90)
for label in ax.get_xaxis().get_ticklabels()[::2]:
    label.set_visible(False)
plt.show()

在此处输入图像描述

标签: matplotlib

解决方案


此设置会将其设置为自动。尝试一下!如果您想进一步自定义它,请参阅此。刻度定位器 刻度格式化程序

更新:当数据和代码都呈现给我时,我再次更新了代码。如果对数据重新排序,它就会变成一个普通图。

import pandas as pd
import numpy as np
import io

data = '''
steps_date mean_step_by_date
26/06/2020 9398.1
27/06/2020 9280.3
28/06/2020 6394.2
29/06/2020 7202.5
30/06/2020 7457.3
20/06/2020 7688.3
21/06/2020 10038
22/06/2020 5889.5
23/06/2020 6960.4
24/06/2020 9915.5
25/06/2020 5796.3
14/06/2020 8699.5
15/06/2020 9733
16/06/2020 8191.5
17/06/2020 12608.5
19/06/2020 7708
18/06/2020 9143.5
08/06/2020 5000
09/06/2020 7251
10/06/2020 3456
11/06/2020 9983
12/06/2020 4523
13/06/2020 10547
'''

s = pd.read_csv(io.StringIO(data),sep='\s+')
s['steps_date'] = pd.to_datetime(s['steps_date'])
s.sort_values('steps_date',ascending=True, inplace=True)

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots()

ax.plot(s['steps_date'], s['mean_step_by_date'])

locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

plt.show()

在此处输入图像描述


推荐阅读