Python matplotlib.dates.YearLocator() Examples

The following are 17 code examples of matplotlib.dates.YearLocator(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.dates , or try the search function .
Example #1
Source File: tearsheet.py    From qstrader with MIT License 5 votes vote down vote up
def _plot_drawdown(self, stats, ax=None, **kwargs):
        """
        Plots the underwater curve
        """
        def format_perc(x, pos):
            return '%.0f%%' % x

        drawdown = stats['drawdowns']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_perc)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.yaxis.grid(linestyle=':')
        ax.xaxis.set_tick_params(reset=True)
        ax.xaxis.set_major_locator(mdates.YearLocator(1))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        ax.xaxis.grid(linestyle=':')

        underwater = -100 * drawdown
        underwater.plot(ax=ax, lw=2, kind='area', color='red', alpha=0.3, **kwargs)
        ax.set_ylabel('')
        ax.set_xlabel('')
        plt.setp(ax.get_xticklabels(), visible=True, rotation=0, ha='center')
        ax.set_title('Drawdown (%)', fontweight='bold')
        return ax 
Example #2
Source File: FranchiseAnimation.py    From FranchiseRevenueComparison with MIT License 5 votes vote down vote up
def set_x_axis_locator(self, x_from, x_to):
        x_axis_range = x_to - x_from
        years = mdates.YearLocator()
        if x_axis_range < 200:
            self.ax.xaxis.set_major_locator(mdates.MonthLocator())
            self.ax.xaxis.set_major_formatter(mdates.DateFormatter('%b-%Y'))
            # self.ax.xaxis.set_major_locator(mdates.AutoDateLocator())
        elif x_axis_range < 7*365:
            self.ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
            self.ax.xaxis.set_major_locator(years)
            self.ax.xaxis.set_minor_locator(mdates.MonthLocator())
        else:
            self.ax.xaxis.set_major_locator(years)
            self.ax.xaxis.set_major_locator(mdates.AutoDateLocator()) 
Example #3
Source File: tearsheet.py    From qstrader with MIT License 5 votes vote down vote up
def _plot_drawdown(self, stats, ax=None, **kwargs):
        """
        Plots the underwater curve
        """
        def format_perc(x, pos):
            return '%.0f%%' % x

        drawdown = stats['drawdowns']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_perc)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.yaxis.grid(linestyle=':')
        ax.xaxis.set_tick_params(reset=True)
        ax.xaxis.set_major_locator(mdates.YearLocator(1))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        ax.xaxis.grid(linestyle=':')

        underwater = -100 * drawdown
        underwater.plot(ax=ax, lw=2, kind='area', color='red', alpha=0.3, **kwargs)
        ax.set_ylabel('')
        ax.set_xlabel('')
        plt.setp(ax.get_xticklabels(), visible=True, rotation=0, ha='center')
        ax.set_title('Drawdown (%)', fontweight='bold')
        return ax 
Example #4
Source File: tearsheet.py    From qstrader with MIT License 5 votes vote down vote up
def _plot_rolling_sharpe(self, stats, ax=None, **kwargs):
        """
        Plots the curve of rolling Sharpe ratio.
        """
        def format_two_dec(x, pos):
            return '%.2f' % x

        sharpe = stats['rolling_sharpe']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_two_dec)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.xaxis.set_tick_params(reset=True)
        ax.yaxis.grid(linestyle=':')
        ax.xaxis.set_major_locator(mdates.YearLocator(1))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        ax.xaxis.grid(linestyle=':')

        if self.benchmark is not None:
            benchmark = stats['rolling_sharpe_b']
            benchmark.plot(
                lw=2, color='gray', label=self.benchmark, alpha=0.60,
                ax=ax, **kwargs
            )

        sharpe.plot(lw=2, color='green', alpha=0.6, x_compat=False,
                    label='Backtest', ax=ax, **kwargs)

        ax.axvline(sharpe.index[252], linestyle="dashed", c="gray", lw=2)
        ax.set_ylabel('Rolling Annualised Sharpe')
        ax.legend(loc='best')
        ax.set_xlabel('')
        plt.setp(ax.get_xticklabels(), visible=True, rotation=0, ha='center')

        return ax 
Example #5
Source File: tearsheet.py    From qstrader with MIT License 5 votes vote down vote up
def _plot_equity(self, stats, ax=None, **kwargs):
        """
        Plots cumulative rolling returns versus some benchmark.
        """
        def format_two_dec(x, pos):
            return '%.2f' % x

        equity = stats['cum_returns']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_two_dec)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.xaxis.set_tick_params(reset=True)
        ax.yaxis.grid(linestyle=':')
        ax.xaxis.set_major_locator(mdates.YearLocator(1))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        ax.xaxis.grid(linestyle=':')

        if self.benchmark is not None:
            benchmark = stats['cum_returns_b']
            benchmark.plot(
                lw=2, color='gray', label=self.benchmark, alpha=0.60,
                ax=ax, **kwargs
            )

        equity.plot(lw=2, color='green', alpha=0.6, x_compat=False,
                    label='Backtest', ax=ax, **kwargs)

        ax.axhline(1.0, linestyle='--', color='black', lw=1)
        ax.set_ylabel('Cumulative returns')
        ax.legend(loc='best')
        ax.set_xlabel('')
        plt.setp(ax.get_xticklabels(), visible=True, rotation=0, ha='center')

        if self.log_scale:
            ax.set_yscale('log')

        return ax 
Example #6
Source File: stock_analysis.py    From intro_ds with Apache License 2.0 5 votes vote down vote up
def drawData(ax, _data):
    """
    使用柱状图表示股市数据
    """
    candlestick_ochl(ax,
        _data[["date2num", "open_price", "close_price", "high_price", "low_price"]].values,
        colorup="r", colordown="g", width=0.5)
    ax.xaxis.set_major_locator(YearLocator())
    ax.xaxis.set_major_formatter(DateFormatter('%Y'))
    return ax 
Example #7
Source File: stochastic_volatility.py    From numpyro with Apache License 2.0 5 votes vote down vote up
def main(args):
    _, fetch = load_dataset(SP500, shuffle=False)
    dates, returns = fetch()
    init_rng_key, sample_rng_key = random.split(random.PRNGKey(args.rng_seed))
    model_info = initialize_model(init_rng_key, model, model_args=(returns,))
    init_kernel, sample_kernel = hmc(model_info.potential_fn, algo='NUTS')
    hmc_state = init_kernel(model_info.param_info, args.num_warmup, rng_key=sample_rng_key)
    hmc_states = fori_collect(args.num_warmup, args.num_warmup + args.num_samples, sample_kernel, hmc_state,
                              transform=lambda hmc_state: model_info.postprocess_fn(hmc_state.z),
                              progbar=False if "NUMPYRO_SPHINXBUILD" in os.environ else True)
    print_results(hmc_states, dates)

    fig, ax = plt.subplots(1, 1)
    dates = mdates.num2date(mdates.datestr2num(dates))
    ax.plot(dates, returns, lw=0.5)
    # format the ticks
    ax.xaxis.set_major_locator(mdates.YearLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    ax.xaxis.set_minor_locator(mdates.MonthLocator())

    ax.plot(dates, jnp.exp(hmc_states['s'].T), 'r', alpha=0.01)
    legend = ax.legend(['returns', 'volatility'], loc='upper right')
    legend.legendHandles[1].set_alpha(0.6)
    ax.set(xlabel='time', ylabel='returns', title='Volatility of S&P500 over time')

    plt.savefig("stochastic_volatility_plot.pdf")
    plt.tight_layout() 
Example #8
Source File: PriceTradeAnalyzer.py    From Stock-Price-Trade-Analyzer with GNU General Public License v3.0 5 votes vote down vote up
def PlotScalerDateAdjust(minDate:datetime, maxDate:datetime, ax):
	if type(minDate)==str:
		daysInGraph = DateDiffDays(minDate,maxDate)
	else:
		daysInGraph = (maxDate-minDate).days
	if daysInGraph >= 365*3:
		majorlocator =  mdates.YearLocator()
		minorLocator = mdates.MonthLocator()
		majorFormatter = mdates.DateFormatter('%m/%d/%Y')
	elif daysInGraph >= 365:
		majorlocator =  mdates.MonthLocator()
		minorLocator = mdates.WeekdayLocator()
		majorFormatter = mdates.DateFormatter('%m/%d/%Y')
	elif daysInGraph < 90:
		majorlocator =  mdates.DayLocator()
		minorLocator = mdates.DayLocator()
		majorFormatter =  mdates.DateFormatter('%m/%d/%Y')
	else:
		majorlocator =  mdates.WeekdayLocator()
		minorLocator = mdates.DayLocator()
		majorFormatter =  mdates.DateFormatter('%m/%d/%Y')
	ax.xaxis.set_major_locator(majorlocator)
	ax.xaxis.set_major_formatter(majorFormatter)
	ax.xaxis.set_minor_locator(minorLocator)
	#ax.xaxis.set_minor_formatter(daysFmt)
	ax.set_xlim(minDate, maxDate) 
Example #9
Source File: tearsheet.py    From qstrader with MIT License 5 votes vote down vote up
def _plot_equity(self, strat_stats, bench_stats=None, ax=None, **kwargs):
        """
        Plots cumulative rolling returns versus some benchmark.
        """
        def format_two_dec(x, pos):
            return '%.2f' % x

        equity = strat_stats['cum_returns']

        if ax is None:
            ax = plt.gca()

        y_axis_formatter = FuncFormatter(format_two_dec)
        ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
        ax.xaxis.set_tick_params(reset=True)
        ax.yaxis.grid(linestyle=':')
        ax.xaxis.set_major_locator(mdates.YearLocator(1))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
        ax.xaxis.grid(linestyle=':')

        equity.plot(lw=2, color='green', alpha=0.6, x_compat=False,
                    label='Strategy', ax=ax, **kwargs)
        if bench_stats is not None:
            bench_stats['cum_returns'].plot(
                lw=2, color='gray', alpha=0.6, x_compat=False,
                label='Benchmark', ax=ax, **kwargs
            )

        ax.axhline(1.0, linestyle='--', color='black', lw=1)
        ax.set_ylabel('Cumulative returns')
        ax.legend(loc='best')
        ax.set_xlabel('')
        plt.setp(ax.get_xticklabels(), visible=True, rotation=0, ha='center')
        return ax 
Example #10
Source File: plot_water_levelui.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
def plot_results(features, dates, water, clouds, save_directory=None, ground_truth_file=None):
    fig, ax = plt.subplots()
    water_line = ax.plot(dates, water, linestyle='-', color='b', linewidth=1,
                         label='Landsat-Generated Surface Area')
    ax.plot(dates, water, 'gs', ms=3)
    # ax.bar(dates, water, color='b', width=15, linewidth=0)
    # ax.bar(dates, clouds, bottom=water, color='r', width=15, linewidth=0)
    ax.xaxis.set_major_locator(mdates.YearLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    ax.xaxis.set_minor_locator(mdates.MonthLocator())
    ax.set_xlabel('Time')
    ax.format_xdata = mdates.DateFormatter('%m/%d/%Y')

    if ground_truth_file is not None:
        (ground_truth_dates, ground_truth_levels) = load_ground_truth(ground_truth_file)
        ax2 = ax.twinx()
        ground_truth_line = ax2.plot(ground_truth_dates, ground_truth_levels, linestyle='--', color='r', linewidth=2, label='Measured Elevation')
        ax2.set_ylabel('Lake Elevation (ft)')
        ax2.format_ydata = (lambda x: '%g ft' % (x))
        ax2.set_ylim([6372, 6385.5])

    def onpick(event):
        thisline = event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        ind = event.ind
        print 'onpick points:', zip(xdata[ind], ydata[ind])
    fig.canvas.mpl_connect('pick_event', onpick)

    ax.format_ydata = (lambda x: '%g km^2' % (x))
    ax.set_ylabel('Lake Surface Area (km^2)')
    fig.suptitle(features['name'] + ' Surface Area from Landsat')
    lns = water_line# + ground_truth_line
    labs = [l.get_label() for l in lns]
    ax.legend(lns, labs, loc=4)

    ax.grid(True)
    fig.autofmt_xdate()

    if save_directory is not None:
        fig.savefig(os.path.join(save_directory, features['name'] + '.pdf')) 
Example #11
Source File: plot_water_level.py    From CrisisMappingToolkit with Apache License 2.0 5 votes vote down vote up
def plot_results(features, dates, water, clouds, save_directory=None, ground_truth_file=None):
    fig, ax = plt.subplots()
    water_line = ax.plot(dates, water, linestyle='-', color='b', linewidth=1,
                         label='Landsat Surface Area')
    ax.plot(dates, water, 'gs', ms=3)
    # ax.bar(dates, water, color='b', width=15, linewidth=0)
    # ax.bar(dates, clouds, bottom=water, color='r', width=15, linewidth=0)
    ax.xaxis.set_major_locator(mdates.YearLocator(2))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    ax.xaxis.set_minor_locator(mdates.MonthLocator([1, 4, 7, 10]))
    ax.set_xlabel('Time')
    ax.format_xdata = mdates.DateFormatter('%m/%d/%Y')
    ax.set_xlim([datetime.date(1984, 1, 1), datetime.date(1984, 12, 31)])
    ax.set_ylim([150, 190])

    lns = water_line
    if ground_truth_file is not None:
        (ground_truth_dates, ground_truth_levels) = load_ground_truth(ground_truth_file)
        ax2 = ax.twinx()
        ground_truth_line = ax2.plot(ground_truth_dates, ground_truth_levels, linestyle='--', color='r', linewidth=2, label='Measured Elevation')
        ax2.set_ylabel('Lake Elevation (ft)')
        ax2.format_ydata = (lambda x: '%g ft' % (x))
        ax2.set_ylim([6372.0, 6385.5])
        lns = lns + ground_truth_line
        ax2.set_xlim([datetime.date(1984, 6, 1), datetime.date(2015, 10, 1)])

    ax.format_ydata = (lambda x: '%g km^2' % (x))
    ax.set_ylabel('Lake Surface Area (km^2)')
    fig.suptitle(features['name'] + ' Surface Area from Landsat')
    labs = [l.get_label() for l in lns]
    ax.legend(lns, labs, loc=4)

    ax.grid(True)
    fig.autofmt_xdate()

    if save_directory is not None:
        fig.savefig(os.path.join(save_directory, features['name'] + '.pdf')) 
Example #12
Source File: Trade_Algo.py    From QTS_Research with MIT License 4 votes vote down vote up
def back_test_plot(self):
        import matplotlib.pyplot as plt
        import matplotlib.dates as mdates
        fig = plt.figure()
        all_lines = []
        ax = fig.add_subplot(111)
        ax.set_ylabel('PnL')
        has_right_ax = False
        if 'quant_index' in self.used_vars or \
            'quant_index1' in self.used_vars or \
            'quant_index2' in self.used_vars or \
            'quant_index3' in self.used_vars:
            has_right_ax = True
        dates = [ x[0] for x in self.pnls['portfolio'] ]
        for v in self.used_vars:
            if 'portfolio' in v:
                all_lines += ax.plot(dates, [x[1] for x in self.pnls[v]],label=v,linewidth=1)

        if has_right_ax:
            right_ax = ax.twinx()
            for v in self.used_vars:
                if 'index' in v:
                    all_lines += right_ax.plot(dates, self.quant_indices[v],label=v,linewidth=1,ls='dotted')
            
            right_ax.set_ylabel('quant_index')

        # format the ticks
        years = mdates.YearLocator()   # every year
        months = mdates.MonthLocator()  # every month
        yearsFmt = mdates.DateFormatter('%Y')

        ax.xaxis.set_major_locator(years)
        ax.xaxis.set_major_formatter(yearsFmt)
        ax.xaxis.set_minor_locator(months)
        datemin = min(dates)
        datemax = max(dates)
        ax.set_xlim(datemin, datemax)
        ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
        ax.grid(True)


        # rotates and right aligns the x labels, and moves the bottom of the
        # axes up to make room for them
        fig.autofmt_xdate()
        fig.tight_layout()
        plt.legend(all_lines,[l.get_label() for l in all_lines],loc='best')
        plt.show() 
Example #13
Source File: TimeSeries.py    From incubator-sdap-nexus with Apache License 2.0 4 votes vote down vote up
def createLinePlot(self):
        nseries = len(self.meta())
        res = self.results()
        meta = self.meta()

        timeSeries = [datetime.fromtimestamp(m[0]["time"] / 1000) for m in res]

        means = [[np.nan] * len(res) for n in range(0, nseries)]

        plotSeries = self.computeOptions().get_plot_series() if self.computeOptions is not None else None
        if plotSeries is None:
            plotSeries = "mean"

        for n in range(0, len(res)):
            timeSlot = res[n]
            for seriesValues in timeSlot:
                means[seriesValues['ds']][n] = seriesValues[plotSeries]

        x = timeSeries

        fig, axMain = plt.subplots()
        fig.set_size_inches(11.0, 8.5)
        fig.autofmt_xdate()

        title = ', '.join(set([m['title'] for m in meta]))
        sources = ', '.join(set([m['source'] for m in meta]))
        dateRange = "%s - %s" % (timeSeries[0].strftime('%b %Y'), timeSeries[-1].strftime('%b %Y'))

        axMain.set_title("%s\n%s\n%s" % (title, sources, dateRange))
        axMain.set_xlabel('Date')
        axMain.grid(True)
        axMain.xaxis.set_major_locator(mdates.YearLocator())
        axMain.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
        axMain.xaxis.set_minor_locator(mdates.MonthLocator())
        axMain.format_xdata = mdates.DateFormatter('%Y-%m-%d')

        plots = []

        for n in range(0, nseries):
            if n == 0:
                ax = axMain
            else:
                ax = ax.twinx()

            plots += ax.plot(x, means[n], color=self.__SERIES_COLORS[n], zorder=10, linewidth=3, label=meta[n]['title'])
            ax.set_ylabel(meta[n]['units'])

        labs = [l.get_label() for l in plots]
        axMain.legend(plots, labs, loc=0)

        sio = StringIO()
        plt.savefig(sio, format='png')
        return sio.getvalue() 
Example #14
Source File: TimeSeriesSolr.py    From incubator-sdap-nexus with Apache License 2.0 4 votes vote down vote up
def createLinePlot(self):
        nseries = len(self.meta())
        res = self.results()
        meta = self.meta()

        timeSeries = [datetime.fromtimestamp(m[0]["time"] / 1000) for m in res]

        means = [[np.nan] * len(res) for n in range(0, nseries)]

        plotSeries = self.computeOptions().get_plot_series() if self.computeOptions is not None else None
        if plotSeries is None:
            plotSeries = "mean"

        for n in range(0, len(res)):
            timeSlot = res[n]
            for seriesValues in timeSlot:
                means[seriesValues['ds']][n] = seriesValues[plotSeries]

        x = timeSeries

        fig, axMain = plt.subplots()
        fig.set_size_inches(11.0, 8.5)
        fig.autofmt_xdate()

        title = ', '.join(set([m['title'] for m in meta]))
        sources = ', '.join(set([m['source'] for m in meta]))
        dateRange = "%s - %s" % (timeSeries[0].strftime('%b %Y'), timeSeries[-1].strftime('%b %Y'))

        axMain.set_title("%s\n%s\n%s" % (title, sources, dateRange))
        axMain.set_xlabel('Date')
        axMain.grid(True)
        axMain.xaxis.set_major_locator(mdates.YearLocator())
        axMain.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
        axMain.xaxis.set_minor_locator(mdates.MonthLocator())
        axMain.format_xdata = mdates.DateFormatter('%Y-%m-%d')

        plots = []

        for n in range(0, nseries):
            if n == 0:
                ax = axMain
            else:
                ax = ax.twinx()

            plots += ax.plot(x, means[n], color=self.__SERIES_COLORS[n], zorder=10, linewidth=3, label=meta[n]['title'])
            ax.set_ylabel(meta[n]['units'])

        labs = [l.get_label() for l in plots]
        axMain.legend(plots, labs, loc=0)

        sio = StringIO()
        plt.savefig(sio, format='png')
        return sio.getvalue() 
Example #15
Source File: plotting.py    From incubator-sdap-nexus with Apache License 2.0 4 votes vote down vote up
def createTimeSeries(res, meta, nseries=1):
    # maxSeries = [m[0]['maxFiltered'] for m in res]
    # minSeries = [m[0]['minFiltered'] for m in res]
    # mean = [m[0]["meanFiltered"] for m in res]
    # mean1 = [m[1]["meanFiltered"] for m in res]
    # stdSeries = [m[0]['std'] for m in res]

    timeSeries = [datetime.datetime.fromtimestamp(m[0]["time"] / 1000) for m in res]

    means = [[np.nan] * len(res) for n in range(0, nseries)]

    for n in range(0, len(res)):
        timeSlot = res[n]
        for seriesValues in timeSlot:
            means[seriesValues['ds']][n] = seriesValues['mean']

    x = timeSeries

    fig, axMain = plt.subplots()
    fig.set_size_inches(11.0, 8.5)
    fig.autofmt_xdate()

    title = ', '.join(set([m['title'] for m in meta]))
    sources = ', '.join(set([m['source'] for m in meta]))
    dateRange = "%s - %s" % (timeSeries[0].strftime('%b %Y'), timeSeries[-1].strftime('%b %Y'))

    axMain.set_title("%s\n%s\n%s" % (title, sources, dateRange))
    axMain.set_xlabel('Date')
    axMain.grid(True)
    axMain.xaxis.set_major_locator(mdates.YearLocator())
    axMain.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
    axMain.xaxis.set_minor_locator(mdates.MonthLocator())
    axMain.format_xdata = mdates.DateFormatter('%Y-%m-%d')

    plots = []

    for n in range(0, nseries):
        if n == 0:
            ax = axMain
        else:
            ax = ax.twinx()

        plots += ax.plot(x, means[n], color=SERIES_COLORS[n], zorder=10, linewidth=3, label=meta[n]['title'])
        ax.set_ylabel(meta[n]['units'])

    labs = [l.get_label() for l in plots]
    axMain.legend(plots, labs, loc=0)

    sio = StringIO()
    plt.savefig(sio, format='png')
    return sio.getvalue() 
Example #16
Source File: TimeSeriesSpark.py    From incubator-sdap-nexus with Apache License 2.0 4 votes vote down vote up
def createLinePlot(self):
        nseries = len(self.meta())
        res = self.results()
        meta = self.meta()

        timeSeries = [datetime.fromtimestamp(m[0]["time"] / 1000) for m in res]

        means = [[np.nan] * len(res) for n in range(0, nseries)]

        plotSeries = self.computeOptions().get_plot_series() if self.computeOptions is not None else None
        if plotSeries is None:
            plotSeries = "mean"

        for n in range(0, len(res)):
            timeSlot = res[n]
            for seriesValues in timeSlot:
                means[seriesValues['ds']][n] = seriesValues[plotSeries]

        x = timeSeries

        fig, axMain = plt.subplots()
        fig.set_size_inches(11.0, 8.5)
        fig.autofmt_xdate()

        title = ', '.join(set([m['title'] for m in meta]))
        sources = ', '.join(set([m['source'] for m in meta]))
        dateRange = "%s - %s" % (timeSeries[0].strftime('%b %Y'), timeSeries[-1].strftime('%b %Y'))

        axMain.set_title("%s\n%s\n%s" % (title, sources, dateRange))
        axMain.set_xlabel('Date')
        axMain.grid(True)
        axMain.xaxis.set_major_locator(mdates.YearLocator())
        axMain.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
        axMain.xaxis.set_minor_locator(mdates.MonthLocator())
        axMain.format_xdata = mdates.DateFormatter('%Y-%m-%d')

        plots = []

        for n in range(0, nseries):
            if n == 0:
                ax = axMain
            else:
                ax = ax.twinx()

            plots += ax.plot(x, means[n], color=self.__SERIES_COLORS[n], zorder=10, linewidth=3,
                             label=meta[n]['title'])
            ax.set_ylabel(meta[n]['units'])

        labs = [l.get_label() for l in plots]
        axMain.legend(plots, labs, loc=0)

        sio = StringIO()
        plt.savefig(sio, format='png')
        return sio.getvalue() 
Example #17
Source File: analysis.py    From web_scraping_and_data_analysis with MIT License 4 votes vote down vote up
def timeline_plot():
    df_ori = pd.read_csv('articles.csv', sep=';', header=None)

    # 取第一列并分割日期与标题
    df = df_ori.iloc[:, 0]
    df = df.str.split(';', expand=True)

    # 格式化日期,设置column,并将日期设置为index
    df.columns = ['date', 'title']
    df.date = pd.to_datetime(df.date)
    df = df.set_index('date')

    # 按月统计文章数"MS"为月初
    cacu = df.resample("MS").count()

    # 画图
    fig, ax = plt.subplots(figsize=[18, 5])

    # 线条
    from pandas.plotting import register_matplotlib_converters
    register_matplotlib_converters()
    ax.plot(cacu, 'o-')

    # fig.autofmt_xdate()

    # 通过设置中文字体方式解决中文展示问题
    font = FontProperties(fname='../common/font/PingFang.ttc', size=18)
    ax.set_title("新世相文章统计", fontproperties=font)
    ax.set_xlabel("日期", fontproperties=font)
    ax.set_ylabel("文章数", fontproperties=font)

    # 设置时间轴
    formater = mdate.DateFormatter('%Y-%m')
    ax.xaxis.set_major_formatter(formater)
    ax.xaxis.set_minor_locator(mdate.MonthLocator())
    ax.xaxis.set_minor_formatter(mdate.DateFormatter('%m'))
    ax.xaxis.set_major_locator(mdate.YearLocator())
    ax.xaxis.set_major_formatter(mdate.DateFormatter('\n\n%Y'))
    # 显示网格
    # ax.xaxis.grid(True, which="minor")
    # ax.yaxis.grid()
    # 显示数值
    # 显示全部数值
    # for a,b in zip(cacu.index, cacu.values):
    #     ax.text(a, b, b[0])
    # 显示最大值
    x = cacu['title'].idxmax()
    y = cacu['title'].max()
    ax.text(x, y, y, verticalalignment='bottom', horizontalalignment='center', fontsize='large')
    # plt.annotate(y, xy=(x,y))
    # 保存图片
    plt.savefig('timeline_analysis.png')
    # 显示图片
    plt.show()