示例#1
0
文件: util.py 项目: zurgeg/obspy
 def __init__(self, *args, **kwargs):
     # the root class of AutoDateFormatter (TickHelper) is an old style
     # class prior to matplotlib version 1.2
     if MATPLOTLIB_VERSION < [1, 2, 0]:
         AutoDateFormatter.__init__(self, *args, **kwargs)
     else:
         super(ObsPyAutoDateFormatter, self).__init__(*args, **kwargs)
     # Reset the scale to make it reproducible across matplotlib versions.
     self.scaled = {}
     self.scaled[1.0] = '%b %d %Y'
     self.scaled[30.0] = '%b %Y'
     self.scaled[365.0] = '%Y'
     self.scaled[1. / 24.] = FuncFormatter(format_hour_minute)
     self.scaled[1. / (24. * 60.)] = \
         FuncFormatter(format_hour_minute_second)
     self.scaled[_seconds_to_days(1)] = \
         FuncFormatter(format_hour_minute_second)
     self.scaled[_seconds_to_days(10)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(1))
     # for some reason matplotlib is not using the following intermediate
     # decimal levels (probably some precision issue..) and falls back to
     # the lowest level immediately.
     self.scaled[_seconds_to_days(2e-1)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(2))
     self.scaled[_seconds_to_days(2e-2)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(3))
     self.scaled[_seconds_to_days(2e-3)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(4))
     self.scaled[_seconds_to_days(2e-4)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(5))
示例#2
0
文件: util.py 项目: junlysky/obspy
 def __init__(self, *args, **kwargs):
     # the root class of AutoDateFormatter (TickHelper) is an old style
     # class prior to matplotlib version 1.2
     if MATPLOTLIB_VERSION < [1, 2, 0]:
         AutoDateFormatter.__init__(self, *args, **kwargs)
     else:
         super(ObsPyAutoDateFormatter, self).__init__(*args, **kwargs)
     # Reset the scale to make it reproducible across matplotlib versions.
     self.scaled = {}
     self.scaled[1.0] = '%b %d %Y'
     self.scaled[30.0] = '%b %Y'
     self.scaled[365.0] = '%Y'
     self.scaled[1. / 24.] = FuncFormatter(format_hour_minute)
     self.scaled[1. / (24. * 60.)] = \
         FuncFormatter(format_hour_minute_second)
     self.scaled[_seconds_to_days(1)] = \
         FuncFormatter(format_hour_minute_second)
     self.scaled[_seconds_to_days(10)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(1))
     # for some reason matplotlib is not using the following intermediate
     # decimal levels (probably some precision issue..) and falls back to
     # the lowest level immediately.
     self.scaled[_seconds_to_days(2e-1)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(2))
     self.scaled[_seconds_to_days(2e-2)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(3))
     self.scaled[_seconds_to_days(2e-3)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(4))
     self.scaled[_seconds_to_days(2e-4)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(5))
示例#3
0
文件: viz.py 项目: apodemus/obstools
    def setup_ticks(self):
        
        #Tick setup for both axes
        minorTickSize = 8
        for axis in (self.yaxis, self.parasite.yaxis):
            axis.set_tick_params('both', tickdir='out')
            #axis.set_tick_params('minor', labelsize=minorTickSize, pad=0)
        
        #TODO:  colors='' #For sidereal time axis
        
        self.xaxis.set_tick_params('major', pad=10)
        self.yaxis.set_tick_params('minor', labelsize=6, pad=5)
        
        
        #Tick setup for main axes
#         self.xaxis.set_tick_params('major', pad=10)
#         self.yaxis.set_tick_params('minor', labelsize=6, pad=5)
        dloc = AutoDateLocator()
        #self.xaxis.tick_bottom()
        self.xaxis.set_major_locator(dloc)
        self.xaxis.set_minor_locator(AutoMinorLocator())
        self.xaxis.set_major_formatter(AutoDateFormatter(dloc))
        
        self.yaxis.set_minor_locator(AutoMinorLocator())
        self.yaxis.set_major_formatter(DegreeFormatter())
        self.yaxis.set_minor_formatter(DegreeFormatter())
        
        #Tick setup for main axes
        
        
        #self.parasite.axis['right'].major_ticklabels.set_visible(False)
        
        
        ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        #def set_formatters(self):
            
        #self.xaxis.set_minor_formatter(ticker.ScalarFormatter())
        self.parasite.xaxis.tick_top()
        self.parasite.xaxis.offsetText.set_visible(False)
        
        dloc = AutoDateLocator()
        self.parasite.xaxis.set_major_locator(dloc)
        #self.parasite.xaxis.set_minor_locator(AutoMinorLocator())
        self.parasite.xaxis.set_major_formatter(AutoDateFormatter(dloc))
        
        #fine grained formatting for coord display subtext
        fgfmt = AutoDateFormatter(dloc)
        fgfmt.scaled[1/24] = '%H:%M:%S'
        self._xcoord_formatter = fgfmt
        
        self._ycoord_formatter = DegreeFormatter(precision=2)
        
        self.parasite.yaxis.tick_right()
        self.parasite.yaxis.set_major_formatter(SeczFormatter())
        
        #self.parasite.yaxis.set_minor_locator(AutoMinorLocator())
        self.parasite.yaxis.set_minor_formatter(SeczFormatter())
示例#4
0
 def __init__(self, locator, tz=None):
     """
     Choose format prefix based on data range.
     Choose whether to include seconds based on unit.
     """
     AutoDateFormatter.__init__(self, locator, tz)
     self.scaled = {
         1./(24*60*60): '%H:%M:%S',
         1.           : '%H:%M',
     }
     self.prefixd = {
         365. : '%Y %b %d ',
         1.   : '%b %d ',
     }
def plot(df, df_prev, xlabel="ds", ylabel="y"):
    from matplotlib import pyplot as plt
    from matplotlib.dates import (
        AutoDateLocator,
        AutoDateFormatter,
    )

    fig = plt.figure(facecolor="w", figsize=(10, 6))
    ax = fig.add_subplot(111)

    fcst_t = pd.to_datetime(df["ds"])
    ax.plot(pd.to_datetime(df_prev["ds"]), df_prev["y"], "k.")
    ax.plot(fcst_t, df["yhat"], ls="-", c="#0072B2")
    if "cap" in df:
        ax.plot(fcst_t, df["cap"], ls="--", c="k")

    if "floor" in df:
        ax.plot(fcst_t, df["floor"], ls="--", c="k")

    ax.fill_between(
        fcst_t, df["yhat_lower"], df["yhat_upper"], color="#0072B2", alpha=0.2
    )
    locator = AutoDateLocator(interval_multiples=False)
    formatter = AutoDateFormatter(locator)
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    ax.grid(True, which="major", c="gray", ls="-", lw=1, alpha=0.2)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    fig.tight_layout()

    return fig
示例#6
0
def draw_chart(x, y, size, format="png", dpi=80, color="#000080", xlim=None):
    from matplotlib.dates import DayLocator, HourLocator, AutoDateFormatter
    from matplotlib import ticker
    import pylab as pl
    f = plt.figure()
    ax = f.add_axes([0, 0, 1, 1])
    if xlim:
        ax.set_xlim(xlim[0], xlim[1])
    else:
        ax.set_xlim(x[0], x[-1])
    ax.plot(x, y)
    formatter = AutoDateFormatter(HourLocator())
    formatter.scaled[(1/24.)] = "%H:%M"
    ax.xaxis.grid(True, which="major")
    ax.yaxis.grid(True, which="major")
    ax.xaxis.set_major_locator(HourLocator())
    ax.xaxis.set_major_formatter(formatter)
    res = cStringIO.StringIO()
    w_inches = size[0] / dpi
    h_inches = size[1] / dpi
    if h_inches <= 0 or w_inches <= 0:
        raise Exception("chart size not allowed!")
    f.autofmt_xdate()
    f.set_size_inches(w_inches, h_inches)
    f.savefig(res, format=format, dpi=dpi, bbox_inches="tight")
    return res.getvalue()
示例#7
0
def plot(m, fcst, splitFlag, ax=None, uncertainty=True, plot_cap=True, xlabel='时间', ylabel='流量',
         figsize=(10, 6)):
    """ prophet 绘图 """
    if ax is None:
        fig = plt.figure(facecolor='w', figsize=figsize)
        ax = fig.add_subplot(111)
    else:
        fig = ax.get_figure()
    fcst_t = fcst['ds'].dt.to_pydatetime()
    ax.plot(m.history['ds'].dt.to_pydatetime(), m.history['y'], 'k.')
    # ax.plot(fcst_t, fcst['yhat'], ls='-', c='#0072B2')
    ax.plot(fcst_t[0: -splitFlag], fcst['yhat'][0: -splitFlag], ls='-', c='#0072B2')
    ax.plot(fcst_t[-splitFlag:], fcst['yhat'][-splitFlag:], ls='-', c='r')
    if uncertainty:
        ax.fill_between(fcst_t, fcst['yhat_lower'], fcst['yhat_upper'],
                        color='#0072B2', alpha=0.2)

    # Specify formatting to workaround matplotlib issue #12925
    locator = AutoDateLocator(interval_multiples=False)
    formatter = AutoDateFormatter(locator)
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    fig.tight_layout()
    return fig
 def plot_hourly(self, context, node_id, limits):
     plt.yscale('log', basey=1000, subsy=range(100, 1000, 100))
     plt.yticks([10**0, 10**3, 10**6, 10**9, 10**12, 10**15, 10**18],
                ['1 B', '1 KB', '1 MB', '1 GB', '1 TB', '1 PB', '1 EB'])
     loc = AutoDateLocator(tz=pytz.timezone('US/Eastern'))
     plt.gca().xaxis.set_major_locator(loc)
     plt.gca().xaxis.set_major_formatter(AutoDateFormatter(loc))
     plt.grid(b=True, axis='x')
     plt.grid(b=True, axis='y', which='both')
     plt.bar(*zip(*context.bytes_per_hour[node_id].items()),
             color='#50a050',
             linewidth=0,
             width=1 / 24.,
             label='total')
     if 80 in context.bytes_per_port_per_hour[node_id]:
         plt.bar(
             *zip(*context.bytes_per_port_per_hour[node_id][80].items()),
             color='#5050a0',
             linewidth=0,
             width=1 / 24.,
             label='HTTP')
     plt.xlabel('Time in EST/EDT')
     plt.ylabel('Bytes transferred per hour')
     plt.legend(prop=dict(size=10))
     plt.ylim(bottom=1)
示例#9
0
def plot_forecast_component(m, fcst, name, ax=None, uncertainty=True, plot_cap=False,
                            figsize=(10, 6), ylabel=""):
    artists = []
    if not ax:
        fig = plt.figure(facecolor='w', figsize=figsize)
        ax = fig.add_subplot(111)
    fcst_t = fcst['ds'].dt.to_pydatetime()
    artists += ax.plot(fcst_t, fcst[name], ls='-', c='#0072B2')
    if 'cap' in fcst and plot_cap:
        artists += ax.plot(fcst_t, fcst['cap'], ls='--', c='k')
    if m.logistic_floor and 'floor' in fcst and plot_cap:
        ax.plot(fcst_t, fcst['floor'], ls='--', c='k')
    if uncertainty:
        artists += [ax.fill_between(
            fcst_t, fcst[name + '_lower'], fcst[name + '_upper'],
            color='#0072B2', alpha=0.2)]
    # Specify formatting to workaround matplotlib issue #12925
    locator = AutoDateLocator(interval_multiples=False)
    formatter = AutoDateFormatter(locator)
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
    ax.set_xlabel('时间')

    ax.set_ylabel(name if ylabel == "" else ylabel)
    if name in m.component_modes['multiplicative']:
        ax = set_y_as_percent(ax)
    return artists
def plot(dataLists, interval):
    fig, ax = plt.subplots()
    for dataList in dataLists:
        addPlot(ax, dataList)
    if type(interval) == int:
        # every day
        locator = DayLocator(interval=interval)
        locatorFmt = AutoDateFormatter(locator)
    else:
        # every month
        locator = MonthLocator(range(1, 13), bymonthday=1, interval=1)
        locatorFmt = DateFormatter("%b '%y")
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(locatorFmt)
    ax.xaxis.set_label_text('date')
    ax.yaxis.set_label_text('words')
    plt.legend()
    plt.title('words sent per day by text')
    ax.autoscale_view()
    #ax.xaxis.grid(False, 'major')
    #ax.xaxis.grid(True, 'minor')
    ax.grid(True)

    fig.autofmt_xdate()

    plt.show()
示例#11
0
    def _make_plot(self):
        try:
            from pandas.plotting._timeseries import (_decorate_axes,
                                                     format_dateaxis)
        except ImportError:
            from pandas.tseries.plotting import _decorate_axes, format_dateaxis
        plotf = self._get_plot_function()
        ax = self._get_ax(0)

        data = self.data
        data.index.name = 'Date'
        data = data.to_period(freq=self.freq)
        index = data.index
        data = data.reset_index(level=0)

        if self._is_ts_plot():
            data['Date'] = data['Date'].apply(lambda x: x.ordinal)
            _decorate_axes(ax, self.freq, self.kwds)
            candles = plotf(data, ax, **self.kwds)
            if PANDAS_0200:
                format_dateaxis(ax, self.freq, index)
            else:
                format_dateaxis(ax, self.freq)
        else:
            from matplotlib.dates import date2num, AutoDateFormatter, AutoDateLocator

            data['Date'] = data['Date'].apply(
                lambda x: date2num(x.to_timestamp()))
            candles = plotf(data, ax, **self.kwds)

            locator = AutoDateLocator()
            ax.xaxis.set_major_locator(locator)
            ax.xaxis.set_major_formatter(AutoDateFormatter(locator))

        return candles
示例#12
0
def plot(
        m,
        fcst,
        ax=None,
        uncertainty=True,
        plot_cap=True,
        xlabel='ds',
        ylabel='y',
        figsize=(10, 6),
        y_column='y',
):
    """Plot the Prophet forecast.

    Parameters
    ----------
    m: Prophet model.
    fcst: pd.DataFrame output of m.predict.
    ax: Optional matplotlib axes on which to plot.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    plot_cap: Optional boolean indicating if the capacity should be shown
        in the figure, if available.
    xlabel: Optional label name on X-axis
    ylabel: Optional label name on Y-axis
    figsize: Optional tuple width, height in inches.

    Returns
    -------
    A matplotlib figure.
    """
    if ax is None:
        fig = plt.figure(facecolor='w', figsize=figsize)
        ax = fig.add_subplot(111)
    else:
        fig = ax.get_figure()
    fcst_t = fcst['ds'].dt.to_pydatetime()
    ax.plot(m.history['ds'].dt.to_pydatetime(), m.history[y_column], 'k.')
    ax.plot(fcst_t, fcst['yhat'], ls='-', c='#0072B2')
    if 'cap' in fcst and plot_cap:
        ax.plot(fcst_t, fcst['cap'], ls='--', c='k')
    if m.logistic_floor and 'floor' in fcst and plot_cap:
        ax.plot(fcst_t, fcst['floor'], ls='--', c='k')
    if uncertainty and m.uncertainty_samples:
        ax.fill_between(fcst_t,
                        fcst['yhat_lower'],
                        fcst['yhat_upper'],
                        color='#0072B2',
                        alpha=0.2)
    # Specify formatting to workaround matplotlib issue #12925
    locator = AutoDateLocator(interval_multiples=False)
    formatter = AutoDateFormatter(locator)
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    fig.tight_layout()
    return fig
示例#13
0
    def plot_column(self,
                    column,
                    region='',
                    state='',
                    city='',
                    ax=None,
                    data_source='Ministério da Saúde',
                    add_moving_average=False,
                    start_date=None,
                    end_date=None):
        '''(String, String, String, String) -> None
        Plota o gráfico de uma métrica em um local selecionado'''

        if self.valid_col(column, data_source):

            df = self.get_df(region, state, city, data_source, start_date,
                             end_date)

            if not df.empty:

                if ax is None:
                    fig = plt.figure(facecolor='w', figsize=(10, 6))
                    ax = fig.add_subplot(111)
                    show = True
                else:
                    fig = ax.get_figure()
                    show = False

                locator = AutoDateLocator(interval_multiples=False)
                formatter = AutoDateFormatter(locator)
                ax.xaxis.set_major_locator(locator)
                ax.xaxis.set_major_formatter(formatter)
                ax.plot(df['date'],
                        df[column],
                        label='%s | %s' %
                        (self.correct_col_name[data_source][column],
                         self.format_location([region, state, city])))

                if add_moving_average:
                    ax.plot(df['date'], df[column].expanding(min_periods=60).mean(), \
                            label='Média Móvel | %s | %s' % (self.correct_col_name[data_source][column], self.format_location( [region, state, city] ) ) )

                if show:
                    fig.legend()
                    plt.show()
            else:
                self.messagebox.show_message(self.not_found_msg(
                    region, state, city),
                                             type='Erro')

        else:
            valid_vals = [
                k for k in self.correct_col_name[data_source] if k != 'date'
            ]
            self.messagebox.show_message(
                '''\nO nome %s não corresponde a uma coluna válida para dados do %s. 
            Os nomes válidos para colunas do conjunto atual são:\n- %s \n''' %
                (data_source, column, '\n- '.join(valid_vals)))
示例#14
0
文件: plotjongmok.py 项目: jaehyek/xa
def plotjongmok(jongmokname, listdatestr, listprice, listdealquantity):

    # first, convert listdatestr to floating date number.
    # 20150321 --> 735678.0
    listnum = [
        date2num(datetime(int(aa / 10000), int((aa % 10000) / 100), aa % 100))
        for aa in listdatestr
    ]

    datemax = max(listnum)
    datemin = min(listnum)

    pricemax = max(listprice)
    pricemin = min(listprice)

    fig, (ax1, ax2) = plt.subplots(2, 1)
    locatorMon = MonthLocator(range(1, 13), bymonthday=1, interval=1)
    locatorday = WeekdayLocator(MONDAY)
    # dateformatter = DateFormatter('%Y-%m-%d')

    ax1.plot_date(listnum, listprice, '-')

    ax1.xaxis.set_major_locator(locatorMon)
    ax1.xaxis.set_major_formatter(AutoDateFormatter(locatorMon))
    ax1.xaxis.set_minor_locator(locatorday)
    ax1.set_title('closed price')
    cursor = Cursor(ax1, useblit=True, color='red', linewidth=1)

    ax2.plot_date(listnum, listdealquantity, '.')
    ax2.vlines(listnum, [0], listdealquantity)
    # ax2.bar(listnum, listdealquantity)
    ax2.xaxis.set_major_locator(locatorMon)
    ax2.xaxis.set_major_formatter(AutoDateFormatter(locatorMon))
    ax2.xaxis.set_minor_locator(locatorday)
    ax2.set_title('deal amount')
    cursor = Cursor(ax2, useblit=True, color='red', linewidth=1)

    # format the coords message box
    ax1.format_xdata = DateFormatter('%Y-%m-%d')
    ax2.format_xdata = DateFormatter('%Y-%m-%d')

    # ax.xaxis.grid(True, 'major')
    fig.autofmt_xdate()
    # plt.title(jongmokname)
    plt.show()
示例#15
0
def plot_trend(m,
               ax=None,
               plot_name="Trend",
               figsize=(10, 6),
               df_name="__df__"):
    """Make a barplot of the magnitudes of trend-changes.

    Args:
        m (NeuralProphet): fitted model.
        ax (matplotlib axis): matplotlib Axes to plot on.
            One will be created if this is not provided.
        plot_name (str): Name of the plot Title.
        figsize (tuple): width, height in inches. Ignored if ax is not None.
             default: (10, 6)
        df_name: name of dataframe to refer to data params from original list of train dataframes (used for local normalization in global modeling)

    Returns:
        a list of matplotlib artists
    """
    artists = []
    if not ax:
        fig = plt.figure(facecolor="w", figsize=figsize)
        ax = fig.add_subplot(111)
    data_params = m.config_normalization.get_data_params(df_name)
    t_start = data_params["ds"].shift
    t_end = t_start + data_params["ds"].scale
    if m.config_trend.n_changepoints == 0:
        fcst_t = pd.Series([t_start, t_end]).dt.to_pydatetime()
        trend_0 = m.model.bias.detach().numpy()
        if m.config_trend.growth == "off":
            trend_1 = trend_0
        else:
            trend_1 = trend_0 + m.model.trend_k0.detach().numpy()

        data_params = m.config_normalization.get_data_params(df_name)
        shift = data_params["y"].shift
        scale = data_params["y"].scale
        trend_0 = trend_0 * scale + shift
        trend_1 = trend_1 * scale + shift
        artists += ax.plot(fcst_t, [trend_0, trend_1], ls="-", c="#0072B2")
    else:
        days = pd.date_range(start=t_start, end=t_end, freq=m.data_freq)
        df_y = pd.DataFrame({"ds": days})
        df_trend = m.predict_trend(df={df_name: df_y})[df_name]
        artists += ax.plot(df_y["ds"].dt.to_pydatetime(),
                           df_trend["trend"],
                           ls="-",
                           c="#0072B2")
    # Specify formatting to workaround matplotlib issue #12925
    locator = AutoDateLocator(interval_multiples=False)
    formatter = AutoDateFormatter(locator)
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    ax.grid(True, which="major", c="gray", ls="-", lw=1, alpha=0.2)
    ax.set_xlabel("ds")
    ax.set_ylabel(plot_name)
    return artists
示例#16
0
def manip_info(sessionName, quiet, line_to_print, var_to_plot):
    """
    This function prints information about a session, and optionally
    plot specified variables.

    It can be accessed from the CLI tool ManipInfo
    """

    if os.path.exists(sessionName + ".db"):
        SavedAsyncSession(sessionName).print_description()
        return

    if sessionName.endswith(".hdf5"):
        N = len(sessionName)
        sessionName = sessionName[0:(N - 5)]

    MI = Manip(sessionName).MI
    if line_to_print is not None:
        if line_to_print >= len(MI.log("t")):
            print("Specified line is out of bound.")
            sys.exit(1)
        format_str = "{:>15} | {:>20}"
        print("Printing saved values on line", line_to_print)
        print(format_str.format("Variable", "Value"))
        varlist = ["Time"]
        varlist += MI.log_variable_list()
        print("-" * 38)
        for varname in varlist:
            valtab = MI.log(varname)
            if isinstance(valtab, (float, int)):
                # might occur if only one line
                print(format_str.format(varname, MI.log(varname)))
            else:
                print(
                    format_str.format(varname,
                                      MI.log(varname)[line_to_print]))
    elif not quiet:
        MI.describe()
    if var_to_plot is not None:
        if var_to_plot in MI.log_variable_list():
            t = epoch2num(MI.log("t"))
            vardata = MI.log(var_to_plot)
            fig = plt.figure()
            xtick_locator = AutoDateLocator()
            xtick_formatter = AutoDateFormatter(xtick_locator)
            ax = plt.axes()
            ax.xaxis.set_major_locator(xtick_locator)
            ax.xaxis.set_major_formatter(xtick_formatter)
            ax.plot(t, vardata, "o-")
            plt.setp(ax.xaxis.get_majorticklabels(), rotation=70)
            fig.subplots_adjust(bottom=0.2)
            plt.ylabel(var_to_plot)
            plt.title(sessionName)
            plt.show()
        else:
            print("Variable", var_to_plot, "does not exist!")
            sys.exit(1)
示例#17
0
    def draw_2(self, id):

        data = libchart.get_chart_data(self.session,
                                       self.dt_start,
                                       self.dt_end,
                                       [[id, datetime.timedelta()]],
                                       daily=True)

        x = []
        y = []
        for k, v in data.iteritems():
            x.append(datetime.datetime.strptime(k, '%Y%m%d0000'))
            if v[0] is None:
                y.append(1)
            else:
                y.append(v[0])

        fig = plt.figure(figsize=(400 / 80, 200 / 80))
        ax = fig.add_subplot(1, 1, 1)
        ax.bar(x, y, width=0.4, align='center', color='blue')
        ax.grid(True, axis='y')

        ax.set_ylim(0)
        locator = AutoDateLocator()
        formatter = AutoDateFormatter(locator)
        formatter.scaled[(1.)] = '%m-%d'
        ax.xaxis.set_major_locator(locator)
        ax.xaxis.set_major_formatter(formatter)

        def yaxis_formatter(y, pos):
            def r(i):
                i = round(i, 2)
                if i == int(i):
                    i = int(i)
                return i

            if y < 1e3:
                return int(y)
            elif y < 1e6:
                return '%sK' % r(y / 1e3)
            else:
                return '%sM' % r(y / 1e6)

        ax.yaxis.set_major_formatter(FuncFormatter(yaxis_formatter))

        for tick in ax.xaxis.get_major_ticks():
            tick.label1.set_size(9)
        for tick in ax.yaxis.get_major_ticks():
            tick.label1.set_size(9)

        f = StringIO.StringIO()
        fig.savefig(f)
        plt.close()
        f.seek(0)
        return f
示例#18
0
 def plot_daily_linear(self, context, node_id, limits):
     loc = AutoDateLocator(tz=pytz.timezone('US/Eastern'))
     plt.gca().xaxis.set_major_locator(loc)
     plt.gca().xaxis.set_major_formatter(AutoDateFormatter(loc))
     plt.bar(*zip(*context.bytes_per_day[node_id].items()),
             color='#50a050',
             linewidth=0,
             width=1)
     plt.xlabel('Time in EST/EDT')
     plt.ylabel('Bytes transferred per day')
     plt.ylim(bottom=1)
示例#19
0
def plot_forecast_component(m,
                            fcst,
                            name,
                            ax=None,
                            uncertainty=True,
                            plot_cap=False,
                            figsize=(10, 6)):
    """Plot a particular component of the forecast.

    Parameters
    ----------
    m: Prophet model.
    fcst: pd.DataFrame output of m.predict.
    name: Name of the component to plot.
    ax: Optional matplotlib Axes to plot on.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    plot_cap: Optional boolean indicating if the capacity should be shown
        in the figure, if available.
    figsize: Optional tuple width, height in inches.

    Returns
    -------
    a list of matplotlib artists
    """
    artists = []
    if not ax:
        fig = plt.figure(facecolor='w', figsize=figsize)
        ax = fig.add_subplot(111)
    fcst_t = fcst['ds'].dt.to_pydatetime()
    artists += ax.plot(fcst_t, fcst[name], ls='-', c='#0072B2')
    if 'cap' in fcst and plot_cap:
        artists += ax.plot(fcst_t, fcst['cap'], ls='--', c='k')
    if m.logistic_floor and 'floor' in fcst and plot_cap:
        ax.plot(fcst_t, fcst['floor'], ls='--', c='k')
    if uncertainty and m.uncertainty_samples:
        artists += [
            ax.fill_between(fcst_t,
                            fcst[name + '_lower'],
                            fcst[name + '_upper'],
                            color='#0072B2',
                            alpha=0.2)
        ]
    # Specify formatting to workaround matplotlib issue #12925
    locator = AutoDateLocator(interval_multiples=False)
    formatter = AutoDateFormatter(locator)
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
    ax.set_xlabel('ds')
    ax.set_ylabel(name)
    if name in m.component_modes['multiplicative']:
        ax = set_y_as_percent(ax)
    return artists
示例#20
0
def update_ticks(axes, coord, components, is_log):
    """
    Changes the axes to have the proper tick formatting based on the type of
    component.

    Returns `None` or the number of categories if components is Categorical.

    Parameters
    ----------
    axes : `~matplotlib.axes.Axes`
        A matplotlib axis object to alter
    coord : { 'x' | 'y' }
        The coordinate axis on which to update the ticks
    components : iterable
        A list of components that are plotted along this axis
    if_log : boolean
        Whether the axis has a log-scale
    """

    if coord == 'x':
        axis = axes.xaxis
    elif coord == 'y':
        axis = axes.yaxis
    else:
        raise TypeError("coord must be one of x,y")

    is_cat = any(comp.categorical for comp in components)
    is_date = any(comp.datetime for comp in components)

    if is_date:
        loc = AutoDateLocator()
        fmt = AutoDateFormatter(loc)
        axis.set_major_locator(loc)
        axis.set_major_formatter(fmt)
    elif is_log:
        axis.set_major_locator(LogLocator())
        axis.set_major_formatter(LogFormatterMathtext())
    elif is_cat:
        all_categories = np.empty((0, ), dtype=np.object)
        for comp in components:
            all_categories = np.union1d(comp.categories, all_categories)
        locator = MaxNLocator(10, integer=True)
        locator.view_limits(0, all_categories.shape[0])
        format_func = partial(tick_linker, all_categories)
        formatter = FuncFormatter(format_func)

        axis.set_major_locator(locator)
        axis.set_major_formatter(formatter)
        return all_categories.shape[0]
    else:
        axis.set_major_locator(AutoLocator())
        axis.set_major_formatter(ScalarFormatter())
示例#21
0
def plot(fcst, ax=None, xlabel="ds", ylabel="y", highlight_forecast=None, line_per_origin=False, figsize=(10, 6)):
    """Plot the NeuralProphet forecast

    Args:
        fcst (pd.DataFrame):  output of m.predict.
        ax (matplotlib axes):  on which to plot.
        xlabel (str): label name on X-axis
        ylabel (str): label name on Y-axis
        highlight_forecast (int): i-th step ahead forecast to highlight.
        line_per_origin (bool): print a line per forecast of one per forecast age
        figsize (tuple): width, height in inches.

    Returns:
        A matplotlib figure.
    """
    fcst = fcst.fillna(value=np.nan)
    if ax is None:
        fig = plt.figure(facecolor="w", figsize=figsize)
        ax = fig.add_subplot(111)
    else:
        fig = ax.get_figure()
    ds = fcst["ds"].dt.to_pydatetime()
    yhat_col_names = [col_name for col_name in fcst.columns if "yhat" in col_name]

    if highlight_forecast is None or line_per_origin:
        for i in range(len(yhat_col_names)):
            ax.plot(ds, fcst["yhat{}".format(i + 1)], ls="-", c="#0072B2", alpha=0.2 + 2.0 / (i + 2.5))

    if highlight_forecast is not None:
        if line_per_origin:
            num_forecast_steps = sum(fcst["yhat1"].notna())
            steps_from_last = num_forecast_steps - highlight_forecast
            for i in range(len(yhat_col_names)):
                x = ds[-(1 + i + steps_from_last)]
                y = fcst["yhat{}".format(i + 1)].values[-(1 + i + steps_from_last)]
                ax.plot(x, y, "bx")
        else:
            ax.plot(ds, fcst["yhat{}".format(highlight_forecast)], ls="-", c="b")
            ax.plot(ds, fcst["yhat{}".format(highlight_forecast)], "bx")

    ax.plot(ds, fcst["y"], "k.")

    # Specify formatting to workaround matplotlib issue #12925
    locator = AutoDateLocator(interval_multiples=False)
    formatter = AutoDateFormatter(locator)
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    ax.grid(True, which="major", c="gray", ls="-", lw=1, alpha=0.2)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    fig.tight_layout()
    return fig
示例#22
0
    def _get_formatter(self, locator, formatter, concise):

        if formatter is not None:
            return formatter

        if concise:
            # TODO ideally we would have concise coordinate ticks,
            # but full semantic ticks. Is that possible?
            formatter = ConciseDateFormatter(locator)
        else:
            formatter = AutoDateFormatter(locator)

        return formatter
示例#23
0
def set_date_ticks(axis, auto=True):
    axis.axis_date()
    if auto:
        timeLocator = AutoDateLocator()
        timeFormatter = AutoDateFormatter(timeLocator)
        timeFormatter.scaled[1. / (24. * 60.)] = '%H:%M:%S'
        timeFormatter.scaled[1. / (24. * 60. * 1000.)] = '%H:%M:%S.%f'
    else:
        timeFormatter = DateFormatter("%H:%M:%S")
        timeLocator = MinuteLocator()

    axis.set_major_locator(timeLocator)
    axis.set_major_formatter(timeFormatter)
示例#24
0
def plot(derivative, baseline=None, log=False, includeComponents=False, includePrimary=True, custom=[]):

    assets = []

    # Add component asset returns
    if (includeComponents):
        assets = derivative.assets[:]

    # Add primary returns
    if (includePrimary):
        assets.append(derivative)

    # Add baseline
    if (baseline is not None):
        assets.append(baseline)

    for userdata in custom:
        assets.append(userdata)

    if (log):
        pnl = lambda x: np.cumsum(np.log((getPeriodReturns(x.returns) + 1).resample('B').agg('prod')))
    else:
        pnl = lambda x: np.cumprod((getPeriodReturns(x.returns) + 1).resample('B').agg('prod'))

    # quarters = MonthLocator([1, 3, 6, 9])
    # allmonths = MonthLocator()
    # mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
    # alldays = DayLocator()              # minor ticks on the days
    # weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
    auto_locator = AutoDateLocator()
    auto_formatter = AutoDateFormatter(auto_locator)

    matplotlib.rcParams['figure.figsize'] = (12.0, 6.0)
    plt.ion()
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    ax.xaxis.set_major_locator(auto_locator)
    # ax.xaxis.set_minor_locator(allmonths)
    ax.xaxis.set_major_formatter(auto_formatter)

    for asset in assets:
        ax.plot(pnl(asset), label=asset.name)

    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    plt.title("Derivative performance")
    plt.legend(loc='best')
    fig.canvas.draw()
    return fig, ax
示例#25
0
    def prophet_plot(self,
                     m,
                     fcst,
                     ax=None,
                     uncertainty=True,
                     plot_cap=True,
                     xlabel='ds',
                     ylabel='y',
                     plot_color='#0072B2',
                     plot_actual=True,
                     label='N Periods',
                     figsize=(10, 6)):

        # Método adaptado do .plot do Prophet.

        if ax is None:
            fig = plt.figure(facecolor='w', figsize=figsize)
            ax = fig.add_subplot(111)
        else:
            fig = ax.get_figure()

        fcst_t = fcst['ds'].dt.to_pydatetime()

        if plot_actual:
            ax.plot(m.history['ds'].dt.to_pydatetime(), m.history['y'], 'k.')

        ax.plot(fcst_t, fcst['yhat'], ls='-', c=plot_color, label=label)

        if 'cap' in fcst and plot_cap:
            ax.plot(fcst_t, fcst['cap'], ls='--', c='k')
        if m.logistic_floor and 'floor' in fcst and plot_cap:
            ax.plot(fcst_t, fcst['floor'], ls='--', c='k')
        if uncertainty and m.uncertainty_samples:
            ax.fill_between(fcst_t,
                            fcst['yhat_lower'],
                            fcst['yhat_upper'],
                            color=plot_color,
                            alpha=0.2)

        # Specify formatting to workaround matplotlib issue #12925
        locator = AutoDateLocator(interval_multiples=False)
        formatter = AutoDateFormatter(locator)
        ax.xaxis.set_major_locator(locator)
        ax.xaxis.set_major_formatter(formatter)
        ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        fig.tight_layout()

        return fig
示例#26
0
def plt_stocks():
    df = pre.preproc()

    fig = plt.figure()
    ax = fig.add_subplot(111)

    xtick_locator = AutoDateLocator()
    xtick_formatter = AutoDateFormatter(xtick_locator)

    df["UNH"].plot()
    df["NKE"].plot()
    ax.xaxis.set_major_locator(xtick_locator)
    ax.xaxis.set_major_formatter(xtick_formatter)
    plt.show()
示例#27
0
 def plot_daily(self, context, node_id, limits):
     plt.yscale('log', basey=1000, subsy=range(100, 1000, 100))
     plt.yticks([10**0, 10**3, 10**6, 10**9, 10**12, 10**15, 10**18],
                ['1 B', '1 KB', '1 MB', '1 GB', '1 TB', '1 PB', '1 EB'])
     loc = AutoDateLocator(tz=pytz.timezone('US/Eastern'))
     plt.gca().xaxis.set_major_locator(loc)
     plt.gca().xaxis.set_major_formatter(AutoDateFormatter(loc))
     plt.bar(*zip(*context.bytes_per_day[node_id].items()),
             color='#50a050',
             linewidth=0,
             width=1)
     plt.xlabel('Time in EST/EDT')
     plt.ylabel('Bytes transferred per day')
     plt.ylim(bottom=1)
示例#28
0
文件: util.py 项目: 3rdcycle/obspy
 def __init__(self, *args, **kwargs):
     # the root class of AutoDateFormatter (TickHelper) is an old style
     # class prior to matplotlib version 1.2
     if get_matplotlib_version() < [1, 2, 0]:
         AutoDateFormatter.__init__(self, *args, **kwargs)
     else:
         super(ObsPyAutoDateFormatter, self).__init__(*args, **kwargs)
     self.scaled[1. / 24.] = FuncFormatter(format_hour_minute)
     self.scaled[1. / (24. * 60.)] = \
         FuncFormatter(format_hour_minute_second)
     self.scaled[_seconds_to_days(10)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(1))
     # for some reason matplotlib is not using the following intermediate
     # decimal levels (probably some precision issue..) and falls back to
     # the lowest level immediately.
     self.scaled[_seconds_to_days(2e-1)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(2))
     self.scaled[_seconds_to_days(2e-2)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(3))
     self.scaled[_seconds_to_days(2e-3)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(4))
     self.scaled[_seconds_to_days(2e-4)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(5))
示例#29
0
 def __init__(self, *args, **kwargs):
     # the root class of AutoDateFormatter (TickHelper) is an old style
     # class prior to matplotlib version 1.2
     if get_matplotlib_version() < [1, 2, 0]:
         AutoDateFormatter.__init__(self, *args, **kwargs)
     else:
         super(ObsPyAutoDateFormatter, self).__init__(*args, **kwargs)
     self.scaled[1. / 24.] = FuncFormatter(format_hour_minute)
     self.scaled[1. / (24. * 60.)] = \
         FuncFormatter(format_hour_minute_second)
     self.scaled[_seconds_to_days(10)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(1))
     # for some reason matplotlib is not using the following intermediate
     # decimal levels (probably some precision issue..) and falls back to
     # the lowest level immediately.
     self.scaled[_seconds_to_days(2e-1)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(2))
     self.scaled[_seconds_to_days(2e-2)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(3))
     self.scaled[_seconds_to_days(2e-3)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(4))
     self.scaled[_seconds_to_days(2e-4)] = \
         FuncFormatter(decimal_seconds_format_x_decimals(5))
示例#30
0
def _plot_longitudinal_pyplot(CDS, nodes, to_datetime, width, height):
    fig, ax = plt.subplots(1, figsize=(width / 100, height / 100), dpi=100)
    periods = []

    node2y = {n: i for i, n in enumerate(nodes)}
    # Loop over data points; create box from errors at each point
    x_column = "time"

    max_x = 0
    min_x = math.inf
    for i in range(len(CDS.data[x_column])):
        if CDS.data["node"][i] in nodes:
            start_x = CDS.data[x_column][i]
            slot_width = CDS.data["duration"][i]
            if to_datetime:
                start_x = date2num(start_x)
                slot_width = date2num(CDS.data[x_column][i] +
                                      slot_width) - start_x
            max_x = max(max_x, start_x + slot_width)
            min_x = min(min_x, start_x)
            rect = Rectangle((start_x, node2y[CDS.data["node"][i]]),
                             width=slot_width,
                             height=0.9,
                             color=CDS.data["color"][i],
                             edgecolor=None)

            periods.append(rect)
    pc = PatchCollection(periods, match_original=True)

    # Add collection to axes
    ax.add_collection(pc)

    if to_datetime:
        locator = AutoDateLocator(minticks=2)
        formatter = AutoDateFormatter(locator)
        ax.xaxis.set_major_locator(locator)
        ax.xaxis.set_major_formatter(formatter)

    ax.set(xlim=(min_x, max_x + (max_x - min_x) / 50),
           ylim=(0, float(len(nodes))))

    if to_datetime:
        plt.xticks(rotation=50)

    if len(nodes) <= 30:
        plt.yticks(np.arange(0.5, float(len(nodes)) + 0.5, 1.0), nodes)
    else:
        ax.set_yticklabels([])
    return plt.gcf()
示例#31
0
    def format(
        self,
        formater: Formatter | None = None,
        *,
        concise: bool = False,
    ) -> Temporal:

        # TODO ideally we would have concise coordinate ticks,
        # but full semantic ticks. Is that possible?
        if concise:
            major_formatter = ConciseDateFormatter(self._major_locator)
        else:
            major_formatter = AutoDateFormatter(self._major_locator)
        self._major_formatter = major_formatter

        return self
示例#32
0
def plot_trend_change(m,
                      ax=None,
                      plot_name="Trend Change",
                      figsize=(10, 6),
                      df_name="__df__"):
    """Make a barplot of the magnitudes of trend-changes.

    Args:
        m (NeuralProphet): fitted model.
        ax (matplotlib axis): matplotlib Axes to plot on.
            One will be created if this is not provided.
        plot_name (str): Name of the plot Title.
        figsize (tuple): width, height in inches. Ignored if ax is not None.
             default: (10, 6)
        df_name: name of dataframe to refer to data params from original list of train dataframes (used for local normalization in global modeling)

    Returns:
        a list of matplotlib artists
    """
    artists = []
    if not ax:
        fig = plt.figure(facecolor="w", figsize=figsize)
        ax = fig.add_subplot(111)
    data_params = m.config_normalization.get_data_params(df_name)
    start = data_params["ds"].shift
    scale = data_params["ds"].scale
    time_span_seconds = scale.total_seconds()
    cp_t = []
    for cp in m.model.config_trend.changepoints:
        cp_t.append(start + datetime.timedelta(seconds=cp * time_span_seconds))
    weights = m.model.get_trend_deltas.detach().numpy()
    # add end-point to force scale to match trend plot
    cp_t.append(start + scale)
    weights = np.append(weights, [0.0])
    width = time_span_seconds / 175000 / m.config_trend.n_changepoints
    artists += ax.bar(cp_t, weights, width=width, color="#0072B2")
    locator = AutoDateLocator(interval_multiples=False)
    formatter = AutoDateFormatter(locator)
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    ax.grid(True, which="major", c="gray", ls="-", lw=1, alpha=0.2)
    ax.set_xlabel("Trend Segment")
    ax.set_ylabel(plot_name)
    return artists
示例#33
0
    def subplotTimeSeries(self, ids=[], cols=1):
        # assemble a list if ids to download data for
        resids = self.tsresults.keys() if len(ids) == 0 else ids

        get_ids = [tsid for tsid in resids if tsid not in self.tsvalues.keys()]
        if len(get_ids) > 0:
            print('Need to prepare the data for one or more of these '
                  'result ids')
            self.readTsValues(get_ids)

        if len(get_ids) > 0:
            print('\n')

        # create the figure
        rows = math.ceil(float(len(resids)) / float(cols))
        fig = plt.figure(figsize=(15, rows * 5))
        fig.subplots_adjust(hspace=.5)

        # plot the results, each in its own subplot
        for i in range(1, len(resids) + 1):
            ax = fig.add_subplot(rows, cols, i)
            res = self.tsresults[resids[i - 1]]
            tsval = self.tsvalues[resids[i - 1]]

            x = list(self.tsvalues[resids[i - 1]]['valuedatetime'])
            y = list(self.tsvalues[resids[i - 1]]['datavalue'])
            title = res.FeatureActionObj.SamplingFeatureObj.SamplingFeatureName
            col_width = 80 / cols - 4
            subtitle = title[:col_width] + ' ...' if len(
                title) > col_width else title
            ax.set_title(subtitle, fontsize=14)

            ax.plot_date(x, y, '-')
            ax.set_ylabel(res.VariableObj.VariableNameCV + " (" +
                          res.UnitsObj.UnitsAbbreviation + ")")

            locator = AutoDateLocator()
            ax.xaxis.set_major_locator(locator)
            ax.xaxis.set_major_formatter(AutoDateFormatter(locator))
            labels = ax.get_xticklabels()
            plt.setp(labels, rotation=30, fontsize=10)

            ax.grid(True)
示例#34
0
 def __init__( self, locator ):
   tz = pytz.timezone( 'UTC' )
   AutoDateFormatter.__init__( self, locator, tz = tz )
示例#35
0
文件: pluto.py 项目: modul/scripts
def baseplot(
    x,
    y,
    fmt="b.",
    figure=None,
    subplot=111,
    grid=True,
    sharex=None,
    sharey=None,
    xmajloc=AutoDateLocator(),
    xminloc=AutoDateLocator(),
    xmajfmt=None,
    xminfmt=NullFormatter(),
    fmtxdata=DateFormatter("%F"),
    fmtydata=None,
    fill_between={"facecolor": "blue", "alpha": 0.08},
    **kwargs
):
    """
	prepares and sets options to plot dates,
	returns matplotlib.figure and matplotlib.axes

	Arguments
	---------
	x             x data (sequence of datetime objects)
	y             y data

	fmt           plot format as understood by matplotlib.plot()
	              default: "b."
	figure        passed to matplotlib.figure, default: None
	subplot       passed to matplotlib.subplot, default: 111
	grid          boolean, turns grid on/off
	sharex        matplotlib.axes object to share x axis with (None)
	sharey        matplotlib.axes object to share y axis with (None)
	
	xmajloc       matplotlib Locator instance to set as 
	              x axis major locator, default: AutoDateLocator
	
	xminloc       matplotlib Locator instance to set as
	              x axis minor locator, default: AutoDateLocator
	
	xmajfmt       matplotlib Formatter or similar to set as
	              x axis major formatter, default: None (->AutoDateFormatter)
	
	xminfmt       matplotlib Formatter or similar to set as
		      x axis minor formatter, default: NullFormatter
	
	fmtxdata      matplotlib Formatter or similar to set as
		      x coordinates formatter, default: DateFormatter(%F)
	
	fmtydata      matplotlib Formatter or similar to set as
	              y coordinates formatter
	
	fill_between  dictionary passed as keyword arguments 
	              to matplotlib.axes.fill_between,
		      default: {"facecolor": "blue", "alpha": 0.08}

	----------------------------------------------
	Any other keyword argument is passed on 
	to matplotlib.pyplot.plot_date().
	----------------------------------------------
	"""

    fig = plt.figure(figure)
    ax = fig.add_subplot(subplot, sharex=sharex, sharey=sharey)
    ax.plot_date(x, y, fmt, **kwargs)

    if len(filter(lambda x: type(x) == int, y)) == len(y):
        ax.set_ylim([0, max(y) + 1])
        fmtydata = fmtydata or FormatStrFormatter("%i")
    else:
        ax.set_ylim([0, max(y) + max(y) / 10.0])
        fmtydata = fmtydata or FormatStrFormatter("%.1f")

    ax.set_xlim(([x[0], x[-1]]))
    ax.grid(grid)

    formatter = AutoDateFormatter(xmajloc)
    formatterscale = {100000: "%Y", 360.0: "%b %y", 90.0: "%b", 29.0: "%b %d", 1 / 24.0: "%H:%M"}
    formatter.scaled = formatterscale
    xmajfmt = xmajfmt or formatter

    ax.xaxis.set_major_locator(xmajloc)
    ax.xaxis.set_minor_locator(xminloc)
    ax.xaxis.set_major_formatter(xmajfmt)
    ax.xaxis.set_minor_formatter(xminfmt)
    ax.fmt_xdata = fmtxdata
    ax.fmt_ydata = fmtydata

    if fill_between and len(fill_between) > 0:
        ax.fill_between(x, y, **fill_between)

    fig.autofmt_xdate()

    return fig, ax
示例#36
0
    def plot(self):
        # check if there is anything to plot
        if len(self.plot_instances) == 0:
            raise SystemExit('no data to plot.')

        if self.args['output_file'] is not None:
            # --output-file means don't depend on X,
            # so switch to a pure-image backend before doing any plotting.
            plt.switch_backend('agg')

        self.artists = []
        plt.figure(figsize=(12,8), dpi=100, facecolor='w', edgecolor='w')
        axis = plt.subplot(111)

        # set xlim from min to max of logfile ranges
        xlim_min = min([pi.date_range[0] for pi in self.plot_instances])
        xlim_max = max([pi.date_range[1] for pi in self.plot_instances])

        if xlim_max < xlim_min:
            raise SystemExit('no data to plot.')

        xlabel = 'time'
        ylabel = ''

        # use timezone of first log file (may not always be what user wants but must make a choice)
        tz = self.logfiles[0].timezone
        tzformat = '%b %d\n%H:%M:%S' if tz == tzutc() else '%b %d\n%H:%M:%S%z'

        locator = AutoDateLocator(tz=tz, minticks=5, maxticks=10)
        formatter = AutoDateFormatter(locator, tz=tz)

        formatter.scaled = {
           365.0  : '%Y',
           30.    : '%b %Y',
           1.0    : '%b %d %Y',
           1./24. : '%b %d %Y\n%H:%M:%S',
           1./(24.*60.): '%b %d %Y\n%H:%M:%S',
        }

        # add timezone to format if not UTC
        if tz != tzutc():
            formatter.scaled[1./24.] = '%b %d %Y\n%H:%M:%S%z'
            formatter.scaled[1./(24.*60.)] = '%b %d %Y\n%H:%M:%S%z'

        for i, plot_inst in enumerate(sorted(self.plot_instances, key=lambda pi: pi.sort_order)):
            self.artists.extend(plot_inst.plot(axis, i, len(self.plot_instances), (xlim_min, xlim_max) ))
            if hasattr(plot_inst, 'xlabel'):
                xlabel = plot_inst.xlabel
            if hasattr(plot_inst, 'ylabel'):
                ylabel = plot_inst.ylabel
        if self.args['output_file'] is None:
            self.print_shortcuts(scatter=isinstance(self.plot_instance, plottypes.ScatterPlotType))

        axis.set_xlabel(xlabel)
        axis.set_xticklabels(axis.get_xticks(), rotation=90, fontsize=9)
        axis.xaxis.set_major_locator(locator)
        axis.xaxis.set_major_formatter(formatter)
            
        axis.set_xlim(date2num([xlim_min, xlim_max]))

        # ylabel for y axis
        if self.args['logscale']:
            ylabel += ' (log scale)'
        axis.set_ylabel(ylabel)

        # title and mtools link
        axis.set_title(self.args['title'] or ', '.join([l.name for l in self.logfiles if l.name != '<stdin>']))
        plt.subplots_adjust(bottom=0.15, left=0.1, right=0.95, top=0.95)
        self.footnote = plt.annotate('created with mtools v%s: https://github.com/rueckstiess/mtools' % __version__, (10, 10), xycoords='figure pixels', va='bottom', fontsize=8)

        handles, labels = axis.get_legend_handles_labels()
        if len(labels) > 0:
            # only change fontsize if supported 
            major, minor, _ = mpl_version.split('.')
            if (int(major), int(minor)) >= (1, 3):
                self.legend = axis.legend(loc='upper left', frameon=False, numpoints=1, fontsize=9)
            else:
                self.legend = axis.legend(loc='upper left', frameon=False, numpoints=1)
        
        if self.args['type'] == 'scatter':
            # enable legend picking for scatter plots
            for i, legend_line in enumerate(self.legend.get_lines()):
                legend_line.set_picker(10)
                legend_line._mt_legend_item = i

        # overwrite y-axis limits if set
        if self.args['ylimits'] != None:
            print self.args['ylimits']
            axis.set_ylim( self.args['ylimits'])

        plt.gcf().canvas.mpl_connect('pick_event', self.onpick)
        plt.gcf().canvas.mpl_connect('key_press_event', self.onpress)
        if self.args['output_file'] is not None:
            plt.savefig(self.args['output_file'])
        else:
            plt.show()
示例#37
0
    def build(self):
        app.logger.info("Generating new graph...")

        app.logger.debug("Configuring the graph...")

        font = {'size': 14}

        mpl.rc('font', **font)
        mpl.rcParams['lines.linewidth'] = 2
        mpl.rcParams['figure.figsize'] = 10, 5
        mpl.rcParams['figure.dpi'] = 100

        self.fig = Figure(facecolor = self.background_color)

        if self.maximize:
            ax = self.fig.add_axes((0, 0, 1, 1))

            # Put the labels on the inside of the graph
            # when plotting a maximized graph


            yticks = ax.yaxis.get_major_ticks()

#            for t in yticks[-2:]
#                t.label.set_visible(False)

#            yticks[-1].label.set_visible(False)
#            yticks[0].label.set_visible(False)

            for tick in yticks:
                tick.set_pad(-22)

            for tick in ax.xaxis.get_major_ticks():
                tick.set_pad(-25)

        else:
            ax = self.fig.add_axes((0.08, 0.1, 0.9, 0.85))

            if self.ylabel:
                ax.set_ylabel('C')

            if self.xlabel:
                ax.set_xlabel('Date')

        ax.tick_params(axis='both', which='major', labelsize=9)

        x=[]
        y=[]

        for r in self.data:
            x.append(datetime.datetime.fromtimestamp(r[0]))
            y.append(r[1])


        adl = AutoDateLocator()
        myformatter = AutoDateFormatter(adl)

        ax.xaxis.set_major_locator(adl)
        ax.xaxis.set_major_formatter(myformatter)

        ax.grid(True)

        myformatter.scaled = {
            365.0 : '%Y',           # view interval > 356 days
            30. : '%b %Y',          # view interval > 30 days but less than 365 days
            1.0 : '%b %d',          # view interval > 1 day but less than 30 days
            1./24. : '%H:%M',       # view interval > 1 hour but less than 24 hours
            1./24./60. : '%M:%S',   # view interval > 1 min but less than 1 hour
            1./24./60./60. : '%S',  # view interval < 1 min
        }

        c = list(self.smooth(y, 9, 'blackman'))

        remove_count = len(c) - len(y)
        del c[0:remove_count/2]
        del c[len(c)-remove_count/2:len(c)]

        with Timer() as duration:
            ax.plot(x, y, 'o', antialiased = True, color = 'black', alpha = 0.2)
            ax.plot(x, c, '-', antialiased = True, color = self.color, alpha = 1)

        app.logger.debug("Ploting a graph took %d ms", duration.miliseconds())

#        if self.maximize:
            # Hide first and last label on both axes
#            ax.get_xticklabels()[0].set_visible(False)
#            ax.get_xticklabels()[-1].set_visible(False)
#            ax.get_yticklabels()[0].set_visible(False)
#            ax.get_yticklabels()[-1].set_visible(False)

        self.fig.autofmt_xdate()

        return self