用间隔均匀的时间戳替换x-ticks

时间:2018-10-06 04:52:11

标签: python pandas matplotlib

我试图在timestamps的{​​{1}}上插入x-axis而不是scatter plot。以下是到目前为止我已经尝试过的方法,但是我在这一行中得到了total seconds

error

示例:

loc, labels = ax.set_xticks(x)

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

注意 我需要使用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) loc, labels = ax.set_xticks(x) newlabels = [str(pd.Timedelta(str(i)+ ' seconds')).split()[2] for i in loc] ax.set_xticks(loc, newlabels) 而不是ax,因为此图称为plt。如果使用图,则subplot将分配给最后一个axis而不是指定的那个。

3 个答案:

答案 0 :(得分:1)

我建议直接使用日期时间,而不用打勾标签。另外使用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

答案 1 :(得分:0)

类似这样的方法将起作用: 编辑:进行更改以确保使用了轴和子图

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()

答案 2 :(得分:0)

我正在猜测,但是如果您要替换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()