我在使用 matplotlib 時遇到了這個問題,我無法隱藏自動生成的、不受歡迎的 xlabels,這些 xlabels 似乎不知從何而來。
這是我的代碼(在重現問題的最小示例中減少了實際代碼):
import datetime as dt
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv("TestData.csv")
# Convert string to pd.Timestamp
data["datetime"] = data["datetime"].transform(lambda d:
dt.datetime.strptime(d, '%Y-%m-%d %H:%M:%S'))
data.set_index("datetime")
# start and end dates of data in CSV
max_date = data["datetime"].max()
min_date = data["datetime"].min()
# make figure
fig = plt.figure(figsize=[24, 12], dpi=300)
ax = data.plot.line(x="datetime",
y="totalAIAD",
color="xkcd:aquamarine")
delta = max_date - min_date # total span of time for the report
time_unit = pd.to_timedelta(5, unit='m') # 5 minute ticks
floor_unit = 'T'
# floor for cleaner ticks
date = min_date.floor(floor_unit)
xticks = []
while date time_unit <= max_date:
date = date time_unit # create date ticks for x axis
xticks.append(date)
ax.axes.set_xticks(xticks)
str_xticks = []
for xtick in xticks:
str_xticks.append(xtick.strftime('%H:%M:%S'))
ax.axes.set_xticklabels(str_xticks, rotation=45, ha='right')
#plt.suptitle("Stream Processor and Anomaly Detector Execution times")
#plt.title("From " min_date.strftime('%Y-%m-%d %H:%M:%S') " to "
# max_date.strftime('%Y-%m-%d %H:%M:%S'))
plt.xlabel(
"Time",
fontdict={
'family': 'monospace',
'color': 'xkcd:black',
'weight': 'normal',
'size': 14,
},
labelpad=6
)
plt.ylabel(
"Delays (ms)",
fontdict={
'family': 'monospace',
'color': 'xkcd:black',
'weight': 'normal',
'size': 14,
},
labelpad=6
)
[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]
# vertical range for values (0 to configured MAX_Y)
plt.ylim((0, 50))
plt.grid(True, axis='y', alpha=0.5)
plt.axhline(y=10, color='r', linestyle='-')
plt.show()
plt.close(fig)
這需要一個TestData.csv:
如您所見,只有我在代碼中設定的 xtick 標簽是紅色的。不受歡迎的(11:30、11:45 和 12:15)不受顏色影響。它們也不受我移除它們的所有嘗試的影響。(我試過ax.set_xticks([]),,,,ax.set_xticklabels([]))。plt.xticks([])ax.xaxis.set_major_locator(ticker.NullLocator())
任何的想法?我失去了擺脫那些標簽的希望。
uj5u.com熱心網友回復:
通過使用以日期為 x 軸的 pandas 繪圖,自動設定AutoDateLocatorand AutoDateFormatter。這些設定了自己的刻度,獨立于set_xticks(并且在縮放時還計算新的刻度)。另請參閱
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424613.html
標籤:Python 熊猫 约会时间 matplotlib 时间戳
上一篇:從矩陣生成散點圖
