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()
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)
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()
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
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(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 _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
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)))
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
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()
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)
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
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
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)
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
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
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())
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
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)
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
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
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)
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()
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()
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
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
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)
def plot_area_mean(self, area, level, plevs, file_dates: list): """Creates plot for mean of added variables at the specified area and pressurelevel.""" vars_to_drop = [var for var in TimeseriesModel.all_variable_names if var not in self.varnames + ['PRESS']] # print(self.dsetpaths) if len(self.dsetpaths) < 2: # raise Exception('Too few Datasets') with dbg: print("Too few Datasets (minimum is 2).") return if len(self.varnames) == 0: # raise Exception('No variable added') with dbg: print("No variables added.") return int_dates = [] for date in file_dates: int_date = date2num(date) int_dates.append(int_date) averages = [] for path in self.dsetpaths: tmp = SDModelAdapter() tmp.open_dset(path=path, dropvars=vars_to_drop) for var in self.varnames: tmp.add_var_to_plot(var) averages.append(tmp.get_mean(area=area, level=level, plevs=plevs)) fig, ax1 = plt.subplots(num='') locator = AutoDateLocator() ax1.xaxis.set_major_locator(locator) ax1.xaxis.set_major_formatter(AutoDateFormatter(locator)) plt.clf() # Add labels etc etc if len(self.varnames) == 1: ax1.plot(int_dates, averages) elif len(self.varnames) == 2: ax1.plot([val[0] for val in averages]) ax2 = ax1.twinx() ax2.plot([val[1] for val in averages]) fig.autofmt_xdate()
def __setup_plot(self): figure = Figure(facecolor='lightgrey') self._axes = figure.add_subplot(111) self._axes.set_title('Timeline') self._axes.set_xlabel('Time') self._axes.set_ylabel('Frequency (MHz)') self._axes.grid(True) locator = AutoDateLocator() formatter = AutoDateFormatter(locator) self._axes.xaxis.set_major_formatter(formatter) self._axes.xaxis.set_major_locator(locator) formatter = ScalarFormatter(useOffset=False) self._axes.yaxis.set_major_formatter(formatter) self._axes.yaxis.set_minor_locator(AutoMinorLocator(10)) self._canvas = FigureCanvas(self._panelPlot, -1, figure) self._canvas.mpl_connect('motion_notify_event', self.__on_motion) Legend.__init__(self, self._axes, self._canvas)
def draw_1(self, id): data = libchart.get_chart_data(self.session, self.dt_start, self.dt_end, [[id, datetime.timedelta()]]) x = [] y = [] for k, v in data.iteritems(): x.append(datetime.datetime.strptime(k, '%Y%m%d%H%M')) y.append(v[0]) if y[0] is None: y[0] = 0 if y[-1] is None: y[-1] = 0 fig = plt.figure(figsize=(1024 / 80, 300 / 80)) ax = fig.add_subplot(1, 1, 1) ax.plot(x, y, color='blue') ax.grid(True, axis='y') ax.set_ylim(0) locator = AutoDateLocator() formatter = AutoDateFormatter(locator) formatter.scaled[(1.)] = '%Y-%m-%d' ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(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, bbox_inches='tight') plt.close() f.seek(0) return f