首页 文章

改变xticks matplotlib

提问于
浏览
1

我有一个散点图,有时间在 x-axis

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import ticker

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

plt.scatter(x_numbers, y)
plt.show()

输出1:
enter image description here

我想换掉实际时间戳的总秒数,所以我包括:

plt.xticks(x_numbers, x)

这导致x-ticks彼此重叠 .

如果我使用:

plt.locator_params(axis='x', nbins=10)

结果与上述相同 . 如果我将 nbins 更改为更小的刻度,则不要将它们与各自的散点对齐 . 与分散点一样,不与正确的时间戳对齐 .

如果我使用:

M = 10
xticks = ticker.MaxNLocator(M)
ax.xaxis.set_major_locator(xticks)

ticks 不要与各自的散点对齐 .

是否可以选择您使用的 x-ticks 的数量,但仍然与相应的数据点对齐 .

例如 . 对于下面的 figure . 我可以只使用 nticks 而不是全部吗?

输出2:

enter image description here

2 回答

  • 1

    让我们使用一些xticklabel操作:

    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())
    
    plt.scatter(x_numbers, y)
    loc, labels = plt.xticks()
    newlabels = [str(pd.Timedelta(str(i)+ ' seconds')).split()[2] for i in loc]
    plt.xticks(loc, newlabels)
    plt.show()
    

    输出:
    enter image description here

  • 0

    首先,时间间隔不一致 . 其次,它是一个高频系列 .

    在一般情况下,您不需要匹配每个条目对应的 xticks . 并且,在这些情况下,您可以利用 plt.plot_date(x, y) 以及tick locatorsformatters 之类的东西, DayLocator()DateFormatter('%Y-%m-%d') .

    虽然对于这种非常特殊的情况,数据处于微小水平并且几个点非常接近,但是黑客可能会尝试使用您用于x轴的数字系列, x_numbers . 为了增加两点之间的差距,我尝试了 cumsum() 并且为了消除重叠到一定程度,给了 rotationxticks .

    fig, ax = plt.subplots(figsize=(10,6))
    
    x = df['A']
    y = df['B']
    
    x_numbers = (pd.to_timedelta(df['A']).dt.total_seconds()).cumsum()
    
    plt.scatter(x_numbers, y)
    plt.xticks(x_numbers, x, rotation=50)
    plt.show()
    

    enter image description here

相关问题