【发布时间】:2019-02-22 07:08:29
【问题描述】:
如何像下图一样增加刻度线之间的间距?
情节 1:设置
数据集
time value
2010-01 1
2010-02 2
2010-03 3
2010-04 4
2010-05 5
2010-06 6
2010-07 7
2010-08 8
2010-09 9
2010-10 8
2011-01 7
2011-02 6
2011-03 5
2011-04 4
2011-05 3
2011-06 2
2011-07 1
2011-08 2
2011-09 3
2011-10 4
2011-11 5
2011-21 6
我的尝试:
在How to: reduce number of ticks with matplotlib 的帖子中,一位用户展示了如何增加刻度标签之间的间距,如下所示:
# Attempt 1
every_nth = 5
for n, label in enumerate(ax.xaxis.get_ticklabels()):
if n % every_nth != 0:
#print(n)
label.set_visible(False)
情节 2:一次尝试
但如您所见,刻度线保持不变。
因此使用该设置,我天真地尝试用ax.get_xticks() 替换ax.xaxis.get_ticklabels() 部分,但到目前为止没有成功:
# in:
for n, tick in enumerate(ax.get_xticks()):
if n % every_nth != 0:
tick.set_visible(False)
# out: AttributeError: 'int' object has no attribute 'set_visible'
ax.tick_params? 中似乎也没有选项。您甚至会在那里找到 padding,但没有关于刻度间距的信息。
任何其他建议都会很棒!通常我会将索引更改为PeriodIndex 并使用import matplotlib.dates as mdates 格式化轴,但我真的想要一种更直接的技术。
这是一个简单的复制和粘贴的全部内容:
#imports
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# df = pd.read_clipboard(sep='\\s+')
# plot setup
fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
plt.xticks(rotation=45)
# Attempt 1
every_nth = 5
for n, label in enumerate(ax.xaxis.get_ticklabels()):
if n % every_nth != 0:
#print(n)
label.set_visible(False)
#every_nth = 5
#for n, tick in enumerate(ax.xaxis.get_ticks()):
# if n % every_nth != 0:
# #print(n)
# tick.set_visible(False)
plt.show()
【问题讨论】:
-
不要试图隐藏刻度,您应该尝试将每 5 个刻度左右放入
plt.xticks(rotation=45)命令中,您可以在其中指定刻度的位置和刻度的标签 -
你没有找到/试过
ax.set_xticks吗?
标签: python matplotlib