如何使用Matplotlib将X轴设置为时间轴

时间:2019-05-29 12:32:32

标签: python pandas matplotlib charts

我正在尝试分析SentinelHub统计API中的数据。 为了制作出精美的图表,我想将X轴格式化为时间间隔为1个月的时间轴。

因此,我正在使用matplotlib,尤其是page上的set_major_locatorMonthLocator

不知道为什么,如果它来自循环,我正在使用它来生成所有图表或其他东西,但是它不起作用。

有人可以帮助我吗?

enter image description here

这是我的代码:

for year in time_df.year:

    charts_folder = '{}/{}_ndvi_charts_{}'.format(folder, os.path.basename(os.path.splitext(shp)[0]), year)

    if os.path.exists(charts_folder):
        shutil.rmtree(charts_folder)
        os.mkdir(charts_folder)
    else:
        os.mkdir(charts_folder)

    for block_id in block_id_list:
        block_df = df_data_noCloud[(df_data_noCloud['block_id'] == block_id) & (df_data_noCloud['year'] == year)]

        block_df = block_df.set_index(['date']).sort_index()

        nb_date = len(block_df)
        window = int(nb_date/2)

        if nb_date > 1:

            if window%2 == 0:
                window = window-1

            if nb_date > 4 and window > 3:
                block_df['ndvilis'] = signal.savgol_filter(block_df['ndvi'], window_length=window, polyorder=3)


            fig, g = plt.subplots(figsize=(20,10))
            plt.gca().set_ylim(0.2, 0.9)

            x = block_df.index
            ndvi = block_df['ndvi']
            ndvimin = block_df['10min']
            ndvimax = block_df['10max']
            ndvilis = block_df['ndvilis']

            ndvig = g.plot(x,ndvi, color='red', linestyle='--', label='NDVI')
            if nb_date > 4 and window > 3:
                ndvilisg = g.plot(x, ndvilis, color='blue', label='NDVI lissé')
            g.plot(x, ndvimax, color='orange', linestyle=':')
            g.plot(x, ndvimin, color='orange', linestyle=':')

            g.set_title('{} block {} - {}'.format(os.path.basename(os.path.splitext(shp)[0]), block_id, year))
            g.set_ylabel('NDVI')

            g.get_xaxis().set_major_locator(mdates.MonthLocator(interval=1))
            g.get_xaxis().set_major_formatter(mdates.DateFormatter("%b %Y"))
            g.set_xticklabels(block_df.index,rotation=90)

            handles, labels = g.get_legend_handles_labels()
            g.legend(handles, labels)

            plt.savefig('{0}/{1}_{3}_block_{2}.png'.format(charts_folder, os.path.basename(os.path.splitext(shp)[0]), block_id, year), dpi=150)

        else:
            img = Image.new('RGB', (600, 100), color = (0, 0, 0))

            #fnt = ImageFont.load('arial.pil')
            d = ImageDraw.Draw(img)
            d.text((10,10), "Not enough data to plot", fill=(255, 255, 255), align = 'center')

            img.save('{0}/{1}_{3}_block_{2}.png'.format(charts_folder, os.path.basename(os.path.splitext(shp)[0]), block_id, year)) 

0 个答案:

没有答案