【问题标题】:y-shift every second xticky-shift 每秒 xtick
【发布时间】:2020-06-15 20:07:38
【问题描述】:

我遇到了重叠 xticks 的问题。我必须在我的情节中放置太多的 xticks,每个刻度都是一个有意义的字符串,所以我不能遗漏一些。我已经将 xticks 旋转了 90°

axis.tick_params(axis ='x', rotation = -90)

我找到了一个解决方案,让所有主要的 xticks 都进行 y 位移:

axis.tick_params(axis='x', which='major', pad=10)

不幸的是,我所有的蜱虫都是主要蜱虫,我不知道如何解决这个问题。最后,我希望每一秒 xtick 都在 y 方向上移动,这样刻度就不会再重叠了。

我不能与你分享完整的代码,但这里是它现在的样子:

【问题讨论】:

标签: python matplotlib


【解决方案1】:

通常您可以将FuncFormattercycle 对象一起使用

In [49]: import numpy as np 
    ...: import matplotlib 
    ...: import matplotlib.pyplot as plt 
    ...: from itertools import cycle 
    ...: %matplotlib tk 
    ...:  
    ...: format_cycle = cycle(['% 3.1f', '% 10.1f', '% 17.1f', '% 10.1f']) 
    ...: @matplotlib.ticker.FuncFormatter 
    ...: def major_formatter(x,pos): return next(format_cycle)%x                          

In [50]: fig, ax = plt.subplots() 
    ...: t = np.linspace(0,6.28, 629) 
    ...: ax.plot(t, np.sin(t)) 
    ...: ax.set_xticks(np.arange(0,6.3, 0.1)) 
    ...: ax.tick_params(axis='x', rotation=-90) 
    ...: ax.xaxis.set_major_formatter(major_formatter) 
    ...: fig.tight_layout()                                                               

In [51]:                                                                                  

在您的用例中,您已经有了标签?因此,只需在将它们传递给ax.set_xticklabels之前在它们前面加上适当数量的空格即可

spaces = cycle(['', '   ', '      ', '   ']) # 0, 3, 6, 3 spaces
ax.set_xticklabels([next(spaces)+label for label in labels])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多