如何让x轴只显示我想绘制的数据?而不是包括没有情节的标签?

2 python matplotlib

我正在绘制日期与整数.但是因为日期范围相隔100天,所以matplotlib会自动包含100天之间的每个日期,即使只有20个左右的数据也可以绘制.所以我的问题是,如何让x轴只生成有数据绘制的日期?此外,目前日期是以横向方式压扁的,我如何以垂直方式获取它们以便更适合?

这是我的图表的图片: 在此输入图像描述

这是我的代码:

    import datetime as dt
    import matplotlib.dates as mdates

    array1 = ['2014-10-28', '2014-11-17', '2014-09-29', '2014-10-17', '2014-10-22']
    array2 = [1,4,5,6,9]

    x = [dt.datetime.strptime(a,'%Y-%m-%d').date() for a in array1]    
    plt.plot_date((x), (array2), 'ro')
    plt.show() 
Run Code Online (Sandbox Code Playgroud)

wil*_*ill 5

好的,首先,您可以使用该fig.autofmt_xdate()功能自动处理xtick标签 - 这是最简单的方法.

所以你会有这样的事情:

import datetime as dt
import matplotlib.dates as mdates
from matplotlib import pyplot
from random import randint


array1 = ['2014-10-28', '2014-11-17', '2014-09-29', '2014-10-17', '2014-10-22']
array2 = [1,4,5,6,9]


dates = ["2014-{month:0>2d}-{day:0>2d}".format(month=m, day=d) for m in [1,5] for d in range(1,32)]
dates = [dt.datetime.strptime(d, '%Y-%m-%d').date() for d in dates]
freqs = [randint(0,4) for _ in dates]

fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)
ax.plot_date(dates, freqs, "ro")

fig.autofmt_xdate()

pyplot.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

仍然有你不想要的大差距,但刻度标签更好.

接下来,为了处理拆分,有一些选项,但它们还不在主要的matplotlib中(我知道).这是通过实际绘制两个图,在中间移除刺,并使用sharey选项来完成的:

import datetime as dt
import matplotlib.dates as mdates
from matplotlib import pyplot
from random import randint
from matplotlib.ticker import MaxNLocator


dates = ["2014-{month:0>2d}-{day:0>2d}".format(month=m, day=d) for m in [1,5] for d in range(1,10)]
dates = [dt.datetime.strptime(d, '%Y-%m-%d').date() for d in dates]
freqs = [randint(0,4) for _ in dates]



fig = pyplot.figure()

ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2, sharey=ax1)

ax1.plot_date(dates, freqs, "ro")
ax2.plot_date(dates, freqs, "ro")


#set the upper and lower bounds for the two adjacent plots
ax1.set_xlim(xmax=dt.datetime.strptime("2014-01-11", '%Y-%m-%d').date())
ax2.set_xlim(xmin=dt.datetime.strptime("2014-05-01", '%Y-%m-%d').date())


for ax in [ax1, ax2]:
  _ = ax.get_xticklabels() #For some reason, if i don't do this, then it only prints years for the tick labels. :/
  ax.xaxis.set_major_locator(mdates.AutoDateLocator(maxticks=6))

#Turn off the spines in the middle
ax1.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)

ax1.yaxis.tick_left()

ax2.get_yaxis().set_visible(False)

pyplot.subplots_adjust(wspace=0.1)

fig.autofmt_xdate()

pyplot.show()
Run Code Online (Sandbox Code Playgroud)

还有一些额外的东西需要清理,但我想你明白了.

在此输入图像描述