x轴不连续时如何去除多余的日期时间pandas DatetimeIndex
how to remove redundant date time when x-axis is incontinuous pandas DatetimeIndex
我想绘制一个 pandas 系列,其索引是无数个 DatatimeIndex。我的代码如下:
import matplotlib.dates as mdates
index = pd.DatetimeIndex(['2000-01-01 00:00:00', '2000-01-01 00:01:00',
'2000-01-01 00:02:00', '2000-01-01 00:03:00',
'2000-01-01 00:07:00',
'2000-01-01 00:08:00'],
dtype='datetime64[ns]')
df = pd.Series(range(6), index=index)
print(df)
plt.plot(df.index, df.values)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%M"))
plt.show()
输出为:
但是结果并不是我真正想要的,因为图像上也绘制了 2000-01-01 00:04:00。期望的结果是在 x 轴上 03:00 紧挨着 07:00 并且图像应该是一条直线。期待你的好主意。
一种可能的解决方案是通过 strftime
and use Series.plot
:
将索引转换为 string
s = pd.Series(range(6), index=index)
print(s)
2000-01-01 00:00:00 0
2000-01-01 00:01:00 1
2000-01-01 00:02:00 2
2000-01-01 00:03:00 3
2000-01-01 00:07:00 4
2000-01-01 00:08:00 5
dtype: int32
s.index = s.index.strftime('%M')
s.plot()
另一种解决方案是通过arange
绘制然后添加xticks
:
x = np.arange(len(s.index))
plt.plot(x, s)
plt.xticks(x, s.index.strftime('%M'))
plt.show()
我想绘制一个 pandas 系列,其索引是无数个 DatatimeIndex。我的代码如下:
import matplotlib.dates as mdates
index = pd.DatetimeIndex(['2000-01-01 00:00:00', '2000-01-01 00:01:00',
'2000-01-01 00:02:00', '2000-01-01 00:03:00',
'2000-01-01 00:07:00',
'2000-01-01 00:08:00'],
dtype='datetime64[ns]')
df = pd.Series(range(6), index=index)
print(df)
plt.plot(df.index, df.values)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%M"))
plt.show()
输出为:
一种可能的解决方案是通过 strftime
and use Series.plot
:
string
s = pd.Series(range(6), index=index)
print(s)
2000-01-01 00:00:00 0
2000-01-01 00:01:00 1
2000-01-01 00:02:00 2
2000-01-01 00:03:00 3
2000-01-01 00:07:00 4
2000-01-01 00:08:00 5
dtype: int32
s.index = s.index.strftime('%M')
s.plot()
另一种解决方案是通过arange
绘制然后添加xticks
:
x = np.arange(len(s.index))
plt.plot(x, s)
plt.xticks(x, s.index.strftime('%M'))
plt.show()