用均匀间隔的时间戳替换xtick

2024-04-25 22:17:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在x-axis上插入scatter plot而不是total seconds。下面是我迄今为止尝试过的方法,但是我用这一行得到了error

loc, labels = ax.set_xticks(x)

AttributeError: 'NoneType' object has no attribute 'update'

示例:

^{pr2}$

注意 我需要使用ax而不是plt,因为这个图被称为subplot。如果我使用plot,axis将被分配给最后一个subplot,而不是指定的一个。在


Tags: 方法labelsploterroraxloctotalattributeerror
3条回答

这样的方法会起作用: 编辑:为确保使用轴和子批次所做的更改

import pandas as pd
import matplotlib.pyplot as plt

d = ({
'A' : ['08:00:00','08:10:00','08:12:00','08:26:00','08:29:00','08:31:00','10:10:00','10:25:00','10:29:00','10:31:00'],
'B' : ['1','1','1','2','2','2','7','7','7','7'],     
'C' : ['X','Y','Z','X','Y','Z','A','X','Y','Z'],
})

df = pd.DataFrame(data=d)
fig,ax = plt.subplots()

x = df['A']
y = df['B']

x_numbers = (pd.to_timedelta(df['A']).dt.total_seconds())


ax.scatter(x_numbers, y)
plt.sca(ax) # gets handle on the current axis
loc, labels = plt.xticks()
plt.xticks(loc, [str(a) for a in x])
plt.show()

我建议直接使用日期时间,而不要弄乱记号标签。另外,使用matplotlib.dates.MinuteLocator可以给你很好的记号位置。在

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

d = ({
    'A' : ['08:00:00','08:10:00','08:12:00','08:26:00','08:29:00','08:31:00',
           '10:10:00','10:25:00','10:29:00','10:31:00'],
    'B' : ['1','1','1','2','2','2','7','7','7','7'],     
    'C' : ['X','Y','Z','X','Y','Z','A','X','Y','Z'],
    })

df = pd.DataFrame(data=d)
df['A'] = pd.to_datetime(df['A'])

fig,ax = plt.subplots()

ax.scatter(df["A"].values, df["B"].values)
ax.set_xlim(df["A"].min(), df["A"].max())

ax.xaxis.set_major_locator(mdates.MinuteLocator((0,30)))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
plt.show()

enter image description here

我在猜测,但如果你想替换x轴标签,试试看。在

import pandas as pd
import matplotlib.pyplot as plt

d = ({
    'A' : ['08:00:00','08:10:00','08:12:00','08:26:00','08:29:00','08:31:00','10:10:00','10:25:00','10:29:00','10:31:00'],
    'B' : ['1','1','1','2','2','2','7','7','7','7'],     
    'C' : ['X','Y','Z','X','Y','Z','A','X','Y','Z'],
    })

df = pd.DataFrame(data=d)
x = df['A']
y = df['B']
x_numbers = (pd.to_timedelta(df['A']).dt.total_seconds())

fig,ax = plt.subplots(figsize=(10,7))
ax.scatter(x_numbers, y)

xLabel = [str(int(num)) + ' seconds' for num in x_numbers]
ax.set_xticklabels(xLabel)

plt.tight_layout() 
plt.show()

相关问题 更多 >