【发布时间】:2021-11-01 00:09:54
【问题描述】:
我对 Matplotlib 很陌生,似乎我不明白如何使用自定义的 x,y 轴绘制图形。 我有一个数据框(请求的 csv 文件),每天有 2 个元素(时间)。我想使用一个 x 轴成对地绘制元素。 这是我的代码:
#creating an example dataframe
low = ['08:20','11:50','09:44','11:12']
high = ['10:45','08:05','11:55','09:10']
low = pd.to_datetime(low).time
high = pd.to_datetime(high).time
col_name = ['lowtide','hightide']
ind_val = pd.date_range(start='01-01-2021',periods=4)
df = pd.DataFrame(data= zip(low,high),columns=col_name,index=ind_val)
print(df)
lowtide hightide
2021-01-01 08:20:00 10:45:00
2021-01-02 11:50:00 08:05:00
2021-01-03 09:44:00 11:55:00
2021-01-04 11:12:00 09:10:00
在 x 轴上应该有一个时间轴,而 y 轴只有低潮和高潮点。 我转置 DataFrame 是因为我不知道如何按行绘制并将 column.names 用作 y 轴值并将每个元素设置为 dtype=str,因为 Matplotlib 争论使用 datetime 对象。
#transpose df for plotting because I don't know how to plot row wise
tides = df.T
print(tides)
2021-01-01 2021-01-02 2021-01-03 2021-01-04
lowtide 08:20:00 11:50:00 09:44:00 11:12:00
hightide 10:45:00 08:05:00 11:55:00 09:10:00
#because of errors while trying to plot I convert all into str
tides = tides.astype(str)
my_xaxis=pd.date_range(start='08:00',end='12:00',freq='5min').time
fig,ax = plt.subplots()
plt.xticks(range(len(my_xaxis)), my_xaxis, rotation='vertical')
plt.yticks(range(len(tides.index)),tides.index)
for column in tides.columns:
plt.plot(tides[column],tides.index)
我想得到的是这样的:
感谢您的帮助
【问题讨论】:
-
我怀疑将所有内容转换为
str是您的问题。你为什么这样做?当你把它们变成字符串时,matplotlib 应该如何将它们绘制成时间? -
我记得我收到一条错误消息,告诉我不能使用 datetime 对象,我应该使用 str 还是 ...? (不记得了)这就是为什么我将所有转换为 str。
标签: python pandas dataframe datetime matplotlib