日期作为图表的横轴:如何格式化标签并设置范围?

问题描述 投票:0回答:1

我有一个程序在.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)
python date matplotlib
1个回答
0
投票

感谢@ImportanceOfBeingErnest,我可以理解:

改进日期格式:

  • 频率:ax.xaxis.set_major_locator(matplotlib.dates.MinuteLocator(interval=60))
  • 格式:ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d/%m %H:%M'))
© www.soinside.com 2019 - 2024. All rights reserved.