def chart_prices(state): forecast = Predispatch() forecast = forecast.get_table("REGION_PRICE") forecast_prices = forecast[forecast['REGIONID'] == state] x_f = forecast_prices['PERIODID'].astype(int) x_f = x_f.apply(convert_to_datetime) # print(type(x_f)) y_f = forecast_prices['RRP'].astype(float) dispatch = Dispatch() dispatch = dispatch.get_table("REGION_PRICE") dispatch_price = dispatch[dispatch["REGIONID"] == state] x_d = pd.to_datetime(dispatch_price['SETTLEMENTDATE'], format='\"%Y/%m/%d %H:%M:%S\"') # print(x_d) y_d = dispatch_price['RRP'].astype(float) fig, (past_ax, forecast_ax) = plt.subplots(1, 2, figsize=(17, 9)) plt.subplots_adjust(wspace=0, hspace=0) past_ax.set_title('Past Prices') past_ax.plot(x_d, y_d, color=blue, lw=3) past_ax.fill_between(x_d, 0, y_d, alpha=.3, color=blue) locator1 = mdates.AutoDateLocator() formatter1 = mdates.ConciseDateFormatter(locator1) past_ax.xaxis.set_major_locator(locator1) past_ax.xaxis.set_major_formatter(formatter1) forecast_ax.set_title('Forecast Prices') # forecast_ax = past_ax.twiny() forecast_ax.plot(x_f, y_f, color=red, lw=3) forecast_ax.fill_between(x_f, 0, y_f, alpha=.3, color=red) locator2 = mdates.AutoDateLocator() formatter2 = mdates.ConciseDateFormatter(locator2) forecast_ax.xaxis.set_major_locator(locator2) forecast_ax.xaxis.set_major_formatter(formatter2) max_y = max([y_f.max(), y_d.max()]) min_y = min([y_f.min(), y_d.min()]) forecast_ax.set_ylim([min_y * 0.9, max_y * 1.1]) past_ax.set_ylim([min_y * 0.9, max_y * 1.1]) forecast_ax.get_yaxis().set_ticklabels([]) forecast_ax.set_xlim(left=x_f.min()) past_ax.set_xlim(right=x_d.max()) fig.suptitle('Wholesale Prices') fig.tight_layout() plt.show()
def setup_axis(ax, origin_date, end_date, h): # x-axis date locators and formatters locator = mdates.AutoDateLocator(maxticks=7) formatter = mdates.ConciseDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) month_fmt = mdates.DateFormatter('%b') def m_fmt(x, pos=None): return month_fmt(x)[:3] ax.xaxis.set_major_locator(mdates.MonthLocator()) ax.xaxis.set_major_formatter(FuncFormatter(m_fmt)) ax.tick_params(axis='x', which='major', width=1, length=5) ax.set_xlim(origin_date, end_date) ax.set_ylim(-h, 1 + h) # Remove the axes spines and the y ticks [s.set_visible(False) for s in ax.spines.values()] [t.set_visible(False) for t in ax.get_yticklines()] [t.set_visible(False) for t in ax.get_yticklabels()] ax.spines['bottom'].set_visible(True) return ax
def _plot(ticker: str, dataframe: pd.DataFrame) -> None: ''' Plots 2 subplots, an equity curve with Bollinger bands and an rsi plot ''' fig, axs = plt.subplots(2, 1, figsize=(10,6)) plt.subplots_adjust(hspace=0.3) locator = mdates.AutoDateLocator(minticks=3, maxticks=20) formatter = mdates.ConciseDateFormatter(locator) ''' characters {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}, which are short-hand notations for shades of blue, green, red, cyan, magenta, yellow, black, and white ''' axs[0].set_title(ticker+' Price') axs[0].xaxis.set_major_locator(locator) axs[0].xaxis.set_major_formatter(formatter) axs[0].plot(dataframe[['BOLU']], c='g', lw=1.5, ls='-.', label='BB-Upper') axs[0].plot(dataframe[['MA_Close']], c='y', lw=1.5, ls='-.', label='MA-Close') axs[0].plot(dataframe[['BOLD']], c='r', lw=1.5, ls='-.', label='BB-Lower') axs[0].plot(dataframe[['close']], c='k', lw=1.5, ls='dotted', label='Close') axs[0].set_ylabel('Price') axs[0].legend(loc=0) axs[0].grid(True) axs[1].set_title(ticker+' RSI') axs[1].xaxis.set_major_locator(locator) axs[1].xaxis.set_major_formatter(formatter) axs[1].set_ylim(0, 100) axs[1].plot(dataframe[['rsi']], c='k', lw=1.5, ls='dotted', label="RSI") axs[1].set_xlabel('Date') axs[1].set_ylabel('rsi') axs[1].legend(loc='lower right') axs[1].grid(True) plt.show()
def plot_data(df, name, event, no_res): fig, ax = plt.subplots(2, 1, constrained_layout=True, figsize=(10, 6)) ax[0].plot(df.timestamp, df.heart_rate, label='HR') ax[0].set_title('Heart Rate') ax[1].plot(df.timestamp, df.power, label='Power') ax[1].plot(df.timestamp, df.power_ma1200, label='20 min moving average') ax[1].plot(df.timestamp, df.power_ma300, label='5 min moving average') ax[1].plot(df.timestamp, df.power_ma60, label='1 min moving average') ax[1].set_title('Power') locator = mdates.AutoDateLocator(minticks=20, maxticks=30) formatter = mdates.ConciseDateFormatter(locator) for a in ax: a.grid(True) a.xaxis.set_major_locator(locator) a.xaxis.set_major_formatter(formatter) a.set_xlabel('Time') a.legend(loc='best') for label in a.get_xticklabels(): label.set_rotation(40) label.set_horizontalalignment('right') if no_res == 1: plt.show() plt.savefig('Plot-' + event + '-' + name + '.png') plt.close()
def plot_var(pp, time, pres, v, label, cmap): # t = [t.timestamp() for t in time] # # fig1, ax1 = plt.subplots() # tcf = ax1.tricontourf(t, pres, v, levels=20, cmap=cmap) # plt.plot(t, pres, 'ko ', markersize=0.1) # fig1.colorbar(tcf) # plt.ylim(100, 0) fig1, ax1 = plt.subplots() locator = dates.AutoDateLocator(minticks=3, maxticks=7) formatter = dates.ConciseDateFormatter(locator) ax1.xaxis.set_major_locator(locator) ax1.xaxis.set_major_formatter(formatter) sc = plt.scatter(time, pres, c=v, cmap=cmap) plt.ylim(100, 0) plt.xlim(time[0], time[-1]) fig1.colorbar(sc) plt.xlabel('date-time') plt.ylabel('pressure (dbar)') plt.title('prawler ' + label + ' profile') #plt.show() pp.savefig(fig1, papertype='a4') plt.close()
def show_new(self, title, zero_min=False, window=7, save_fig=False, save_csv=False, figsize=None, ax=None): _figsize = figsize or self.figsize fig, ax = TimeSeriesViz.config_axis(title=self._get_title(title), xgrid=False, figsize=_figsize, ax=ax) diff = self.diff() ax.bar(diff.index, diff, align='center', width=1) sma = diff.rolling(window, center=True).mean() ax.plot(sma.index, sma, color='tab:red', lw=2) ax.set_xlim((diff.index.min() + pd.Timedelta(days=.5), diff.index.max() + pd.Timedelta(days=.5))) locator = mdates.MonthLocator(interval=1) ax.xaxis.set_major_locator(locator) ax.xaxis.set_minor_locator(mdates.DayLocator(interval=1)) ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator)) if zero_min: ax.set_ylim((0, None)) if save_fig: self._save_fig('new') if save_csv: self._save_csv(diff.to_frame(), 'new') return fig, ax
def auto_dates(): locator = mdates.AutoDateLocator() formatter = mdates.ConciseDateFormatter(locator) formatter.formats = [ "%y", # ticks are mostly years "%b", # ticks are mostly months "%d", # ticks are mostly days "%H:%M", # hrs "%H:%M", # min "%S.%f", ] # secs # these are mostly just the level above... formatter.zero_formats = [""] + formatter.formats[:-1] # ...except for ticks that are mostly hours, then it is nice to have # month-day: formatter.zero_formats[3] = "%d-%b" formatter.offset_formats = [ "", "%Y", "%b %Y", "%d %b %Y", "%d %b %Y", "%d %b %Y %H:%M", ] return (locator, formatter)
def plot_timeseries(times, RMs, position=None, savename=None): """Makes a figure plotting the RM variation over time, If savename contains a string it will save the plots to that filename (unless the name is 'screen', in which case it will plot on screen), otherwise the plots are not saved. If position ([ra,dec]) is given, it will be printed above the plots. Args: times (astropy Time array): ionosphere sampling times RMs (array): ionospheric RMs at each time (in rad/m^2) position (list): [ra, dec] in degrees, left blank if not supplied. savename (str): File path to save plot to; if 'screen' will send to display. """ from matplotlib import pyplot as plt from matplotlib import dates as mdates plot_times = times.plot_date fig, ax1 = plt.subplots(1, 1, figsize=(8, 8)) ax1.plot_date(plot_times, RMs, fmt='k.') locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) ax1.xaxis.set_major_locator(locator) ax1.xaxis.set_major_formatter(formatter) ax1.set_ylabel('$\phi_\mathrm{ion}$ [rad m$^{-2}$]') if position is not None: ax1.set_title("RA: {:.2f}°, Dec: {:.2f}°".format( position[0], position[1])) if savename is not None: if savename == "screen": plt.show() else: plt.savefig(savename, bbox_inches='tight')
def thanksgod(): """Thanks God with capital "G" for this decent date/datetime/time x-labels.""" axis = plt.gca() locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) axis.xaxis.set_major_locator(locator) axis.xaxis.set_major_formatter(formatter)
def visualize(self, file=None, save=True): if file is None: df = pandas.read_csv(self.file, sep=',') else: df = pandas.read_csv(file, sep=',') df.set_index('time', inplace=True) df.index = pandas.to_datetime(df.index) ax = df.plot(style='.-') plt.grid() ax.xaxis_date() ax.set_ylim([0, 1.01]) locator = mdates.AutoDateLocator(maxticks=24) formatter = mdates.ConciseDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) if save: fig = plt.gcf() fig.set_size_inches(20, 10) file = self.directory + "/{}_{}_{}.png".format( self.start.year, self.start.month, self.start.day) plt.savefig(file) else: plt.show()
def concise_date_formatter(ax, axis="x", minticks=3, maxticks=7, **kwargs): """ Parameters ---------- ax: matplotlib Axes minticks, maxticks: int, optional """ import matplotlib.dates as mdates if maxticks < minticks: maxticks = minticks + 5 if axis == "x": axis = ax.xaxis if axis == "y": axis = ax.yaxis locator = mdates.AutoDateLocator(minticks=minticks, maxticks=maxticks) formatter = mdates.ConciseDateFormatter(locator, **kwargs) axis.set_major_locator(locator) axis.set_major_formatter(formatter) [tt.set_rotation(0) for tt in axis.get_ticklabels()]
def pumpsStep(instance, qnlp, qconvex=None): fig, axs = plt.subplots(nrows=len(instance.pumps) + 1, ncols=1, sharex=True, figsize=(8,(len(instance.pumps)+1)*1.5)) # fig.suptitle(instance.name, fontsize=14) x = instance.periods qmax = max(p.qmax for p in instance.pumps.values()) * 1.1 for n, (a, p) in enumerate(instance.pumps.items()): qnlpa = [qt[a] for t, qt in qnlp.items()] qnlpa.append(qnlpa[-1]) axs[n].step(x, qnlpa, where='post', color='#557f2d', label='real flow in $m^3/h$') axs[n].set_ylabel(f'({a[0]},{a[1]})', bbox=dict(fc='#557f2d', alpha=0.2, pad=3), fontsize=10) axs[n].set_ylim(0, qmax) axs[n].fill_between(x, p.qmin, p.qmax, color='#557f2d', alpha=0.2) eleccost = [instance.eleccost(t) for t in instance.horizon()] eleccost.append(eleccost[-1]) axs[-1].step(x, eleccost, where='post', color='#7f6d5f', label='elec in 'u"\u20AC"'/MWh') axs[-1].set_ylim(min(0, min(eleccost)), max(eleccost) * 1.1) locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) axs[-1].xaxis.set_major_locator(locator) axs[-1].xaxis.set_major_formatter(formatter) axs[-1].set_xlim(x[0], x[-1]) plt.tight_layout() axs[0].set_title('pump flow in $m^3/h$', fontsize=9) axs[-1].set_title('electricity cost in 'u"\u20AC"'/MWh', fontsize=9) fig.show()
def pumpsGratien(instance, qnlp, qconvex=None): opacity = 0.6 barwidth = 0.0375 * instance.tsinhours() box = dict(facecolor='blue', pad=3, alpha=0.3) fig, axs = plt.subplots(len(instance.pumps) + 1, 1, sharex=True, figsize=(8,(len(instance.pumps)+1)*1.5)) # fig.suptitle(instance.name, fontsize=14) x = instance.periods[:-1] for n, a in enumerate(instance.pumps): qnlpa = [qt[a] for t, qt in qnlp.items()] axs[n].bar(x, qnlpa, barwidth, alpha=opacity, color='blue', edgecolor='black', label='real flow in $m^3/h$') if qconvex: qcona = [qt[a] for t, qt in qconvex.items()] axs[n].bar(x, qcona, barwidth, alpha=opacity, color='red', label='flow in $m^3/h$') axs[n].set_ylabel(f'({a[0]},{a[1]})', bbox=box, fontsize=10) opacity = 0.6 eleccost = [instance.eleccost(t) for t in instance.horizon()] axs[-1].bar(x, eleccost, barwidth, alpha=opacity, color='red', label='elec in 'u"\u20AC"'/MWh') axs[-1].set_ylim([min(min(eleccost) * 1.1, -max(eleccost) * 0.1), max(eleccost) * 1.1]) locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) axs[-1].xaxis.set_major_locator(locator) axs[-1].xaxis.set_major_formatter(formatter) plt.tight_layout() axs[0].set_title('pump flow in $m^3/h$', fontsize=9) axs[-1].set_title('electricity cost in 'u"\u20AC"'/MWh', fontsize=9) fig.show()
def plot_graph(T, Last): fig, ax = plt.subplots() try: #plt.plot(T, Last) Last.plot() except Exception as e: print("Error plotting graph") # Formatting the xaxis - Dates locator = mdates.AutoDateLocator(maxticks=8) formatter = mdates.ConciseDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) # Formatting the yaxis - $$ ax.yaxis.set_major_formatter('${x:,.2f}') ax.yaxis.set_tick_params(which='major', labelcolor='green', labelleft=True, labelright=False) #graph = mpld3.fig_to_html(fig) #return graph imgdata = StringIO() fig.savefig(imgdata, format='svg', bbox_inches="tight") imgdata.seek(0) graph = imgdata.getvalue() return graph
def tick(ax, xmaj=None, xmin=None, ymaj=None, ymin=None, zmaj=None, zmin=None, date=None): """ Adds linearly spaced ticks to ax. """ if not xmin: xmin = xmaj / 5. if xmaj else None if not ymin: ymin = ymaj / 5. if xmaj else None if xmaj: ax.xaxis.set_major_locator(plt.MultipleLocator(xmaj)) if xmin: ax.xaxis.set_minor_locator(plt.MultipleLocator(xmin)) if ymaj: ax.yaxis.set_major_locator(plt.MultipleLocator(ymaj)) if ymin: ax.yaxis.set_minor_locator(plt.MultipleLocator(ymin)) if zmaj: ax.zaxis.set_major_locator(plt.MultipleLocator(zmaj)) if zmin: ax.zaxis.set_minor_locator(plt.MultipleLocator(zmin)) if date: locator = dates.AutoDateLocator(minticks=5, maxticks=10) formatter = dates.ConciseDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) return ax
def plot_scatter(): distance = np.array([row.distance for row in workout]) average_speed = np.array([row.average_speed for row in workout]) calories = np.array([row.calories_burned for row in workout]) climb = np.array([row.climb for row in workout]) pace = np.array([row.average_pace for row in workout]) date_np = np.array([row.date for row in date], dtype='datetime64') # Plotting distance time-series data df = pd.DataFrame( list(zip(date_np, distance, average_speed, calories, climb, pace)), columns=['Date', 'Distance', 'Speed', 'Calories', 'Climb', 'pace']).set_index('Date') fig, ax = plt.subplots(figsize=(8.8, 4), layout='constrained', facecolor=(.18, .31, .31)) ax.set_facecolor('#eafff5') ax.plot(df.index, df.Distance, 'xkcd:crimson', label='Distance raw data') ax.plot(df.Distance.rolling(window=12).mean(), label='Distance rolling mean') ax.plot(df.pace.rolling(window=12).mean(), label='Pace rolling mean miles/hr') ax.legend() ax.set_title('Daily distance vs. time chart', color='0.7') ax.set_xlabel('time (date)', color='c') ax.set_ylabel('distance (miles)', color='peachpuff') ax.xaxis.set_major_formatter( mdates.ConciseDateFormatter(ax.xaxis.get_major_locator())) ax.xaxis.set_minor_locator(AutoMinorLocator()) ax.tick_params(which='both', width=2) ax.tick_params(which='major', length=7) ax.tick_params(which='minor', length=4, color='r') ax.tick_params(labelcolor='tab:orange') plt.show()
def __create_plot(self, x, y, title, xlabel, ylabel, xticks, plot_type = 'line'): filename = str(uuid.uuid4()) + ".png" temp_path = os.path.join(temp_dir, filename) fig, ax = plt.subplots(figsize = ( 8 , 5.5 )) # Create plot of selected type sns.set_style("whitegrid") if plot_type == 'box': sns.boxplot(x=x, y=y) elif plot_type == 'area': sns.lineplot(x=x, y=y) plt.fill_between(x.values, y.values) elif plot_type == 'bar': sns.barplot(x=x, y=y) else: sns.lineplot(x=x, y=y) # Set plot display parameters plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) if xlabel == 'Date': # Use date formatting to conform to the timescale of the given data locator = mdates.AutoDateLocator(minticks=4, maxticks=14) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator)) plt.xlim(min(x), max(x)) elif plot_type == 'area': plt.xlim(0, 90) elif plot_type == 'line': plt.xticks(xticks) plt.xlim(min(x) - 1, max(x) + 1) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.xticks(rotation=45) plt.savefig(temp_path, format='png') plt.close() # Upload image to public storage bucket if self.storage_type == 'azure': img_url = self.img_storage.upload_blob(temp_path) # Default to local path in static directory else: static_path = 'images/plots/' + filename local_path = os.path.normpath(os.path.join(os.getcwd(), 'static', static_path)) # Ensure the directory exists os.makedirs(os.path.dirname(local_path), exist_ok=True) # Copy the temp file to the static images folder shutil.copyfile(temp_path, local_path) # Generate flask url for the image img_url = url_for('static', filename=static_path) # Cleanup temp file os.remove(temp_path) return img_url
def _plot(ticker: str, ticker_data: pd.DataFrame) -> None: ''' Plots an equity curve with short and long moving average lines ''' fig, axs = plt.subplots(1, 1, figsize=(10, 6)) locator = mdates.AutoDateLocator(minticks=3, maxticks=20) formatter = mdates.ConciseDateFormatter(locator) ''' characters {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}, which are short-hand notations for shades of blue, green, red, cyan, magenta, yellow, black, and white ''' axs.set_title(ticker + ' Price') axs.xaxis.set_major_locator(locator) axs.xaxis.set_major_formatter(formatter) axs.plot(ticker_data[['ma_short']], c='c', lw=1.5, ls='-.', label='MA-Short') axs.plot(ticker_data[['ma_long']], c='b', lw=1.5, ls='-.', label='MA-Long') axs.plot(ticker_data[['close']], c='k', lw=1.5, ls='dotted', label='Close') axs.set_ylabel('Price') axs.legend(loc=0) axs.grid(True) plt.show()
def visualise_crash(self, x_date, bn_stats, crash_date, save=''): (V, SD, AC) = bn_stats fig = plt.figure("Crash information", figsize=(12, 6)) locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) fig.suptitle('Crash information using bottleneck distance') ax = fig.add_subplot(1, 3, 1) ax.plot(x_date, V) ax.set_title('Variance') ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) ax = fig.add_subplot(1, 3, 2) ax.plot(x_date, SD) ax.set_title('Spectrum') ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) ax = fig.add_subplot(1, 3, 3) ax.plot(x_date, AC) ax.set_title('ACF(1)') ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) sys.stdout.write(f'Plot stats on the crash ({crash_date})\n') sys.stdout.flush() plt.draw() if save: fig.savefig(save) plt.pause(0.001) input("Press [enter] to continue.")
def graficar(df, quant, Lden): %matplotlib qt pd.plotting.register_matplotlib_converters() locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) style.use('ggplot') fig, ax = plt.subplots(figsize=[15, 5]) ax.plot(df['Global'], color='r', label='Valores globales') ax.set_ylabel('$L_{eqA} [dBA]$') ax.set_ylim(bottom=0) ax.legend() ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) if isinstance(quant, pd.DataFrame) or isinstance(Lden, pd.DataFrame): fig2, ax2 = plt.subplots(figsize=[15, 5]) ax2.plot(df['Global'], color='r', label='Valores globales', zorder=1) lim_l = df.index[0] lim_r = df.index[-1] if isinstance(quant, pd.DataFrame): i = 0 for q in quant.iterrows(): col_set = 'm' if i == 1: col_set = 'c' i += 1 ax2.hlines(q[1]['Global'], xmin=ax2.get_xlim()[0], xmax=ax2.get_xlim()[1], linestyles='-.', color=col_set, label='Percentil ' + str(int(q[0]*100)), zorder=2) if isinstance(Lden, pd.DataFrame): ax2.hlines(Lden.loc['Lden']['Global'], xmin=ax2.get_xlim()[0], xmax=ax2.get_xlim()[1], linestyles='--', color='g', label='$L_{den}$', zorder=2) ax2.xaxis.set_major_locator(locator) ax2.xaxis.set_major_formatter(formatter) ax2.set_ylim(bottom=0) ax2.set_xlim(left=lim_l, right=lim_r) ax2.legend() return
def graph(self): if not self.run: self.backtest() # plot config plt.style.use('seaborn-darkgrid') # style palette = plt.get_cmap('Set1') # line colors fig, ax = plt.subplots(constrained_layout=True) locator = mdates.AutoDateLocator() # date formatter on axis formatter = mdates.ConciseDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) plt.title("Backtester", loc='left', fontsize=14, fontweight=0, color='black') plt.ylabel("Portfolio Value ($)") # plot algos for index, ticker in enumerate(self.portfolios): ax.plot(self.dates, self.portfolio_values[ticker], marker='', color=palette(index), linewidth=2, alpha=0.9, label=ticker) plt.legend(loc=2, ncol=2) # legend top left plt.show() return
def concise_date(ax=None, minticks=3, maxticks=10, show_offset=True, **kwargs): """ Better date ticks using matplotlib's ConciseDateFormatter. Parameters ---------- ax : axis handle Handle to axis (optional). minticks : int Minimum number of ticks (optional, default 6). maxticks : int Maximum number of ticks (optional, default 10). show_offset : bool, optional Show offset string to the right (default True). Note ---- Currently only works for x-axis See Also -------- matplotlib.mdates.ConciseDateFormatter : For formatting options that can be used here. """ if ax is None: ax = plt.gca() locator = mdates.AutoDateLocator(minticks=minticks, maxticks=maxticks) formatter = mdates.ConciseDateFormatter( locator, show_offset=show_offset, **kwargs ) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter)
def chart(db, title, desc, sensor, interval, unit): res = db.get_series(desc, sensor, interval)[desc] sns.set_context("talk", font_scale=0.5) plot = sns.lineplot(data=res) plot.set(title=title, frame_on=False, label=desc) plot.grid(ls="--") plot.tick_params(width=0) plot.xaxis.set_major_locator(mdates.HourLocator()) plot.xaxis.set_major_formatter(mdates.ConciseDateFormatter(mdates.HourLocator())) plot.yaxis.set_major_formatter(FormatStrFormatter("%.1f\u2009{}".format(unit))) plot.legend().remove() fig = plot.get_figure() fig.set_tight_layout(True) fig.set_size_inches(7.15, 4.5) fig.autofmt_xdate() buf = BytesIO() fig.savefig(buf, dpi=200) fig.clf() buf.seek(0) return Image.open(buf)
def plot_stats(df, output_name, ylabel='rho'): print('\ndf for plotting:\n', df) # ndata = df.shape[1] colors = plt.cm.get_cmap('Set1', None).colors fig, ax = plt.subplots(1, 1, figsize=(10, 6.5)) for column, color in zip(df.columns, colors): plt.plot(df.index, df[column], '-o', color=color, label=column, linewidth=6, markersize=8) locator = matplotlib.dates.AutoDateLocator(minticks=5, maxticks=20) formatter = mdates.ConciseDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) fig.autofmt_xdate() # ax.set_xlim([datetime.date(2019, 11, 15), datetime.date(2020, 7, 1)]) ax.set_xlabel('datetime') ax.set_ylabel(ylabel) ax.legend(loc='upper left') plt.tight_layout() plt.grid() plt.savefig(output_name, dpi=600) plt.show()
def plot_exercise_progress(exercise_name): dates, values = get_exercise_data(exercise_name) fig, ax = pl.subplots(1) formatter = mdates.ConciseDateFormatter(mdates.AutoDateLocator()) ax.xaxis.set_major_formatter(formatter) ax.plot(str_to_datenums(dates), values[:, 0]) pl.show()
def save_plot(self, style="-", title="", xlabel=None, ylabel=None, prefix=None): # {{{ """ Stores the plot of the data collected up to now. """ if prefix is None: prefix = self.prefix fig, ax = plt.subplots() # Code I don't understand that magically formats the x axis locator = mdates.AutoDateLocator(minticks=3, maxticks=9) formatter = mdates.ConciseDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) ax.set_xlim([self.today, self.today + timedelta(days=1)]) ax.set_ylabel(ylabel) ax.set_xlabel(xlabel) ax.set_title(f"{title} {self.today_string}") ax.plot_date(self.x, self.y, style) self.fig_full_path = f"{self.path}{prefix}.png" fig.savefig(self.fig_full_path) plt.close(fig)
def save_plot(ax, title, y_label, x_label, var_name, plot_type_name, plot_time_range, filename_in, output_dir): # Points of interest to mark on plot (In CDT) sunrise = dt.datetime(2017, 8, 21, 6, 10, 32) eclipse_start = dt.datetime(2017, 8, 21, 11, 57) totality_start = dt.datetime(2017, 8, 21, 13, 26) totality_end = dt.datetime(2017, 8, 21, 13, 28) eclipse_end = dt.datetime(2017, 8, 21, 14, 52) sunset = dt.datetime(2017, 8, 21, 19, 30, 16) markers = [eclipse_start, totality_start, totality_end, eclipse_end] #markers = [sunrise, eclipse_start, totality_start, totality_end, eclipse_end, sunset] for mark in markers: ax.axvline(mark, color='r', linewidth=0.5) # Format ax.set_title(title) ax.set_ylabel(y_label) ax.set_xlabel(x_label) ax.legend() locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) plt.tight_layout() # Generate filename domain_level = filename_in.split('/')[-1].split('_')[1] start_time = plot_time_range[0].strftime("%d%b%Y_%H%M") end_time = plot_time_range[-1].strftime("%d%b%Y_%H%M") fig_name = var_name + "_" + plot_type_name + "_" + domain_level + "_" + start_time + "to" + end_time + ".png" print("\t" + fig_name) plt.savefig(output_dir + fig_name)
def doubling(k, b): confidence = 0.95 window = confirmedTs[k - b:k] x = range(len(window)) y = [math.log(f) for f in window.values] slope, intercept, r_value, p_value, se = scipy.stats.linregress(x, y) n = len(x) h = se * scipy.stats.t.ppf((1 + confidence) / 2., n - 1) DT = math.log(2) / slope DTMin = math.log(2) / (slope + h) DTMax = math.log(2) / (slope - h) fig6 = plt.figure(facecolor='w') ax6 = fig6.add_subplot(111, axisbelow=True) locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) ax6.xaxis.set_major_locator(locator) ax6.xaxis.set_major_formatter(formatter) ax6.plot(confirmedTs, '-', color='r', alpha=0.5, lw=2) ax6.set_xlabel('Fecha') ax6.set_ylabel('Casos') date_time = current_date.strftime("%d/%m/%Y") strTitle = 'Casos COVID19 (Guatemala)\nEscala Logarítmica' ax6.set_title(strTitle) ax6.yaxis.set_tick_params(length=0) ax6.xaxis.set_tick_params(length=0) ax6.set_yscale('log') ax6.grid(b=True, which='both', c='0.75', alpha=0.2, lw=2, ls='-') for spine in ('top', 'right', 'bottom', 'left'): ax6.spines[spine].set_visible(False) filename = 'doubling.png' plt.savefig(RESULTS_DIR + filename) plt.savefig(IMG_DIR + filename) plt.close() return DT, DTMin, DTMax, r_value**2
def plot_data(): distance = np.array([row.distance for row in workout]) date_np = np.array([row.date for row in date], dtype='datetime64') # Plotting distance time-series data df = pd.DataFrame(list(zip(date_np, distance)), columns=['Date', 'Distance']).set_index('Date') fig, ax = plt.subplots(figsize=(8.8, 4), layout='constrained', facecolor=(.18, .31, .31)) ax.set_facecolor('#eafff5') ax.plot(df.index, df.Distance, 'xkcd:crimson', label='raw data') ax.plot(df.Distance.rolling(window=12).mean(), label='rolling mean') ax.legend() secax_x = ax.secondary_xaxis('top', functions=(date2yday, yday2date)) secax_x.set_xlabel('Number of days') ax.set_title('Daily distance vs. time chart', color='0.7') ax.set_xlabel('time (date)', color='c') ax.set_ylabel('distance (miles)', color='peachpuff') ax.xaxis.set_major_formatter( mdates.ConciseDateFormatter(ax.xaxis.get_major_locator())) ax.xaxis.set_minor_locator(AutoMinorLocator()) ax.tick_params(which='both', width=2) ax.tick_params(which='major', length=7) ax.tick_params(which='minor', length=4, color='r') ax.tick_params(labelcolor='tab:orange') plt.show()
def plot_variable(data_at_levels: dict, vars: PlotVariables, only_surface=False): fig, ax = plt.subplots() for level, data in data_at_levels.items(): data = data[(data["time"] >= pd.Timestamp('2018-09-13 21:00:00')) & (data["time"] <= pd.Timestamp('2018-09-14 06:00:00'))] plt.plot(data["time"], data[vars.column], label=level) if only_surface: break plt.legend() ax.set_xlabel("Time Interval Start") ax.set_ylabel(vars.y_label) plt.xlim(pd.Timestamp('2018-09-13 21:00:00'), pd.Timestamp('2018-09-14 06:00:00')) # ax.xaxis.set_major_locator(mdates.HourLocator(interval=3)) ax.xaxis.set_major_formatter( mdates.ConciseDateFormatter(mdates.HourLocator(interval=3))) from calculations.simple_time_averaging import get_dissipation_formation_times dissipation, formation = get_dissipation_formation_times() for line1, line2 in zip(formation, dissipation): ax.axvspan(line1, line2, alpha=0.2, color='blue') plt.title(vars.plot_title) plt.savefig(vars.output_path) plt.close()