隐藏特定的x轴刻度标签

时间:2015-04-20 14:37:24

标签: python matplotlib

我有兴趣在最后一个散点和Y2(右)脊柱之间添加更多空间,而不是将该点紧邻脊柱(参见附件PNG enter image description here)。

我可以通过在plt.ticks命令中添加一年来添加所需的空间,但是然后" 2017"显示我不想要的。

是否有办法(a)使用现有命令在最后一个散点图和脊柱之间添加空格,或者(b)使用我尝试的方法并隐藏或使最后一个标签与背景颜色匹配,或者(c) )因为我是matplotlib的新手,并且我不熟悉所有术语,请将我引导到现有的链接?

提前致谢。

plt.xticks(["1975-01-01", "1980-01-01", "1985-01-01", "1990-01-01", "1995-01-01", "2000-01-01", "2005-01-01", "2010-01-01", "2015-01-01", "2017-01-01"])

1 个答案:

答案 0 :(得分:1)

我发现使用datetime个对象会在正确的位置给出刻度而不直接修改plt.ticks

import matplotlib.pyplot as plt
from datetime import datetime

# A few example data points
dates = ['1979-04-3', '1990-05-06', '2000-12-12', '2015-04-20']
dates = [datetime.strptime(date, '%Y-%m-%d') for date in dates]
y = [200, 315, 401, 513]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(dates, y, 'd')
ax.set_ylim(0,800)

# set the x-axis limits explicitly, using datetime objects
xmin = datetime.strptime('1975-01-01', '%Y-%m-%d')
xmax = datetime.strptime('2017-01-01', '%Y-%m-%d')
ax.set_xlim(xmin, xmax)

plt.show()

如果你确实需要更好地控制x-ticks,你可以用5年间隔将它们设置为1975-2015(含)年份:

ax.set_xticks([datetime.strptime(str(y), '%Y') for y in range(1975,2020,5)])

enter image description here

相关问题