日期作为图表的水平轴:如何设置标签格式和设置范围?

时间:2019-03-13 14:34:15

标签: python date matplotlib

我有一个程序在.png中生成以下图形: enter image description here

我的问题是:

  • 如何在代码中改进日期格式(我尝试过 ax2.fmt_xdata = matplotlib.dates.DateFormatter('%m-%d %H'),但不起作用...

  • 为什么在图形末尾有空白区域,有什么方法可以将其删除?

我的代码:

def generer_graph(chemin, chemin_graph='',
                  y_low_min=0.02, y_low_max=0.12,
                  y_high_min=600, y_high_max=1000):


    Logger.warning('generer graph: chemin : {}'.format(chemin))
    if chemin_graph == "":
        nom_graph = chemin[:-3:]+'png'
    else:
        nom_graph = chemin_graph+".png"
    Logger.warning('generer_graph: nom_graph : {}'.format(nom_graph))
    #sns.set_style("darkgrid")

    dataframe = pd.read_csv(chemin, sep=';') #decimal=',')


    ordonnee = dataframe['Value']

    abcisse = dataframe['date-time']
    abcisse = pd.to_datetime(dataframe['date-time'], 
                             format='%Y-%m-%d %H:%M:%S.%f').astype(datetime)

    plt.plot(abcisse, ordonnee, marker=',')

    func, (ax, ax2) = plt.subplots(2, 1, sharex=True)
    ax.plot(abcisse, ordonnee, linewidth=1) #graphe du haut
    ax2.plot(abcisse, ordonnee, linewidth=1) #graphe du bas

    # zoom-in / limit the view to different portions of the data
    ax.set_ylim(float(y_high_min), float(y_high_max))  # outliers only
    ax2.set_ylim(float(y_low_min), float(y_low_max))  # most of the data

    # rotate and align the tick labels so they look better
    func.autofmt_xdate()


    # use a more precise date string for the x axis locations in the
    # toolbar
    ax2.fmt_xdata = matplotlib.dates.DateFormatter('%m-%d %H')


    # hide the spines between ax and ax2
    ax.spines['bottom'].set_visible(False)
    ax2.spines['top'].set_visible(False)
    ax.xaxis.tick_top()
    ax.tick_params(labeltop='off')  # don't put tick labels at the top
    ax2.xaxis.tick_bottom()

    diag = .015  # how big to make the diagonal lines in axes coordinates
    # arguments to pass to plot, just so we don't keep repeating them
    kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)
    ax.plot((-diag, +diag), (-diag, +diag), **kwargs)        # top-left diagonal
    ax.plot((1 - diag, 1 + diag), (-diag, +diag), **kwargs)  # top-right diagonal
    kwargs.update(transform=ax2.transAxes)  # switch to the bottom axes
    ax2.plot((-diag, +diag), (1 - diag, 1 + diag), **kwargs)  # bottom-left diagonal
    ax2.plot((1 - diag, 1 + diag), (1 - diag, 1 + diag), **kwargs)  # bottom-right diagonal
    func.suptitle(str(chemin))
    plt.xlabel('Date')
    plt.ylabel('Conso (en mA)')
    plt.savefig(nom_graph)

1 个答案:

答案 0 :(得分:0)

由于@ImportanceOfBeingErnest,我可以弄清楚了:

改进日期格式:

  • 频率:ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d/%m %H:%M'))
  • format:{{1}}