簡體   English   中英

在 matplotlib 中繪制時間的 X 代碼問題

[英]X tickers problem with plotting against time in matplotlib

我正在嘗試通過導入的 csv 文件的數據編寫定義 function 到 plot 的折線圖。

這是我數據的一小部分樣本(每分鍾的溫度讀數):-

00:01:00.0305040, 35.35985
00:02:00.0438094, 35.48547
00:03:00.0571148, 35.65295
00:04:00.0704203, 35.90417
00:05:00.0837257, 36.23914
.
.
.
.
08:52:07.2370729, 74.92772
08:53:07.2503783, 75.01146
08:54:07.2648837, 75.05333
08:55:07.2781891, 75.0952
08:56:07.2914945, 75.0952

當我嘗試將 x 代碼設置為每小時出現一次時,它們不會出現在繪圖中。

這是我的代碼

df = pd.read_csv(file,names=["time", "temp"])
df["time"]=pd.to_datetime(df["time"])
df=df.set_index('time')
df.index = df.index.map (lambda t: t.strftime('%H:%M'))
print(df)
fig, ax = plt.subplots()
df.plot(ax = ax, color = 'black', linewidth = 0.4, x_compat=True)
ax.set(xlabel='Time (Hour:Minutes)', ylabel='Temperature (Celsius)')
ax.xaxis.set_major_locator(mdates.HourLocator(interval = 1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
fig.autofmt_xdate()
return plt.show()

我嘗試手動標記 x 代碼

plt.xticks(['0:00', '1:00', '2:00', '3:00', '4:00:0', '5:00', '6:00:0', '7:00', '8:00', '9:00', '10:00'])

並且它有效,但是對於任何給定的情況都有辦法嗎?

根據官方文檔

所有繪圖函數都需要 np.array 或 np.ma.masked_array 作為輸入。 類似“數組”的類,例如 pandas 數據對象和 np.matrix 可能會也可能不會按預期工作。 最好在繪圖之前將它們轉換為 np.array 對象。

所以我稍微改變了你的代碼(基本上將 pd df 轉換為 numpy 數組)。

df = pd.read_csv(file,names=["time", "temp"])
df["time"]=pd.to_datetime(df["time"])
x_axis = np.array(df.time.values)
y_axis = np.array(df.temp.values)
fig, ax = plt.subplots()
ax.plot(x_axis,y_axis)
ax.set(xlabel='Time (Hour:Minutes)', ylabel='Temperature (Celsius)')
ax.xaxis.set_major_locator(mdates.HourLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
plt.show()

現在可以看到刻度線,如下所示。

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM