我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.dates.DateFormatter()。
def getFigureByXY(x,y): ylabel='\nOutput, MBps' fig = Figure(figsize=(16,6), dpi=120) axis = fig.add_subplot(1, 1, 1) axis.plot(x, y, color='#2b8ef9') axis.fill_between(x,y, facecolor='#2b8ef9') axis.grid(True) axis.set_ylim(bottom=0) axis.set_ylabel(ylabel) # axis.set_xlabel('\n%s - %s' % (x[0],x[-1])) axis.xaxis.set_major_formatter(dates.DateFormatter('%H:%M')) axis.xaxis.set_major_locator(dates.HourLocator(byhour=range(0,24,1))) fig.autofmt_xdate() fig.set_facecolor('white') return fig
def generate_subplots(self, rows: int) -> None: """Generate vertically stacked subplots for comparing data""" # TODO: Experimenting with generating multiple plots, work with Chris on this class # def set_x_formatter(axes): # print("Xlimit changed") # axes.get_xaxis().set_major_formatter(DateFormatter('%H:%M:%S')) # Clear any current axes first self._axes = [] for i in range(rows): if i == 0: sp = self.figure.add_subplot(rows, 1, i+1) # type: Axes else: # Share x-axis with plot 0 sp = self.figure.add_subplot(rows, 1, i + 1, sharex=self._axes[0]) # type: Axes sp.grid(True) sp.name = 'Axes {}'.format(i) # sp.callbacks.connect('xlim_changed', set_x_formatter) self._axes.append(sp) i += 1 self.compute_initial_figure()
def setPlot(self,axe,seriex,seriey,seriex_selec,seriey_selec,serie_type,serie_unit): """ plot a single station """ axe.clear() axe.grid(True) if serie_type=='gravity' and seriey_selec: mean_g=np.mean(seriey_selec) axe.plot([seriex[0],seriex[len(seriex)-1]],[mean_g,mean_g],'o-',color='b',label=serie_type) axe.plot(seriex,seriey,'o-',color='k',label=serie_type) axe.plot(seriex_selec,seriey_selec,'o-',color='b',label=serie_type) axe.set_ylabel(serie_unit, size='x-small') axe.set_title(serie_type, size='x-small') labels = axe.get_xticklabels() + axe.get_yticklabels() for label in labels: label.set_size('x-small') xfmt = md.DateFormatter('%H:%M') axe.xaxis.set_major_formatter(xfmt) plt.setp(axe.get_xticklabels(), rotation=30, horizontalalignment='right') self.canvas.draw()
def plot_timeseries(DF, ax, name, startDate, stopDate, ylim=False): """ plots timeseries graphs """ # original time series ax.plot(DF[name],color='#1f77b4') ax.set_ylabel(name) ax.set_ylim(ylim) ax.set_xlim(pd.datetime.strptime(startDate,'%Y-%m-%d'),\ pd.datetime.strptime(stopDate,'%Y-%m-%d')) # boxcar average ax.plot(DF[name].rolling(180).mean(),color='red') # make the dates exact ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
def __init__(self, tick_minutes, alignment_period=None, per_series_aligner=None, major_formatter=mdates.DateFormatter('%H:%M')): """Visual configuration for the time interval to display in a graph. Args: major_tick_minutes: (int) The number of minutes between each tick. alignment_period: (Optional str) E.g., "120s". The size of each point's bucket of data. If None is provided, each point in the graph will refer to a moment in time rather than a bucket of time. Min is 60s. per_series_aligner: (Optional str) E.g., "ALIGN_MAX". The aligner to use for each series. major_formatter: (Optional matplotlib.Formatter) The formatter for each major tick mark's x-axis time label. Defaults to one that turns an X point into HH:MM e.g., "17:35". """ self.tick_minutes = tick_minutes self.alignment_period = alignment_period self.per_series_aligner = per_series_aligner self.major_formatter = major_formatter
def graphRawFX(): date, bid, ask = np.loadtxt('data/GBPUSD1d.txt', unpack=True, delimiter=',', converters={0: mdates.strpdate2num('%Y%m%d%H%M%S')} ) fig = plt.figure(figsize=(10,7)) ax1 = plt.subplot2grid((40, 40), (0, 0), rowspan=40, colspan=40) ax1.plot(date, bid) ax1.plot(date, ask) plt.gca().get_yaxis().get_major_formatter().set_useOffset(False) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S')) for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) ax1_2 = ax1.twinx() ax1_2.fill_between(date, 0, (ask-bid), facecolor='g', alpha=.3) plt.subplots_adjust(bottom=.23) plt.grid(True) plt.show()
def showResult(date, scales, power, time_scale, window, file_name): # y_ticks = np.arange(0, 15, 2) import matplotlib.ticker as mticker import matplotlib.dates as mdates fig, ax = plt.subplots() ax.xaxis.set_major_locator(YearLocator(time_scale)) # ax.set_yticks(y_ticks) ax.xaxis.set_major_locator(mticker.MaxNLocator(5)) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) ax.contourf(date, scales, power, 100) # ax.set_yscale('log') print("Wavelet saved to", file_name) fig.savefig(file_name) # fig.show() # fig.waitforbuttonpress()
def plotCandlestick(symbol, dates, title="Selected data"): quotes = loadStockQuotes(symbol, dates) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() ax.set_title(title) plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
def plotCandlestick(symbol, startdate, enddate, title="Selected data"): quotes = loadStockQuotes(symbol, startdate, enddate) print(quotes) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 # dayFormatter = DateFormatter('%d') # e.g., 12 fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() ax.set_title(title) plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
def plotCandlestick(symbol, start_index, end_index, title="Selected data"): dates = pd.date_range(start_index, end_index) quotes = utl.loadStockQuotes(symbol, dates) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
def percent_change_as_time_plot(adjusted_df, security): """ This function visualizes the percentage change data as a time series plot. :param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change. :param security: <SecurityInfo class> Holds information about the requested security """ pct_change_list = adjusted_df['Percentage Change'].tolist() date_list = adjusted_df.index.values fig, ax = plt.subplots() ax.plot(date_list, pct_change_list) plt.xlabel("Dates") plt.ylabel("Percentage change from last period") if security.get_period() == "none": plt.title("Percentage change in " + security.get_name(), y=1.03) else: plt.title("Percentage change in " + security.get_name() + " " + security.get_period() + " data", y=1.03) ax.xaxis.set_minor_locator(MonthLocator()) ax.yaxis.set_minor_locator(MultipleLocator(1)) ax.fmt_xdata = DateFormatter('%Y-%m-%d') ax.autoscale_view() fig.autofmt_xdate() plt.show()
def percent_change_as_time_plot(adjusted_df): """ This function visualizes the percentage change data as a time series plot. :param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change. """ pct_change_list = adjusted_df['Percentage Change'].tolist() date_list = adjusted_df.index.values fig, ax = plt.subplots() ax.plot(date_list, pct_change_list) #ax.plot(date_list, adjusted_df["Adjusted Close"]) plt.xlabel("Years") plt.ylabel("Percentage change from last week") plt.title("Percentage change in S&P 500 weekly data from 2009 to 2016") ax.xaxis.set_minor_locator(MonthLocator()) ax.yaxis.set_minor_locator(MultipleLocator(1)) ax.fmt_xdata = DateFormatter('%Y-%m-%d') ax.autoscale_view() fig.autofmt_xdate() plt.show()
def percent_change_as_time_plot(adjusted_df): """ This function visualizes the percentage change data as a time series plot. :param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change. """ pct_change_list = adjusted_df['Percentage Change'].tolist() date_list = [dt.datetime.strptime(d, '%Y-%m-%d').date() for d in adjusted_df['Date'].tolist()] fig, ax = plt.subplots() ax.plot(date_list, pct_change_list) plt.xlabel("Years") plt.ylabel("Percentage change from last week") plt.title("Percentage change in S&P 500 weekly data from 2009 to 2016") ax.xaxis.set_minor_locator(MonthLocator()) ax.yaxis.set_minor_locator(MultipleLocator(1)) ax.fmt_xdata = DateFormatter('%Y-%m-%d') ax.autoscale_view() fig.autofmt_xdate() plt.show()
def savePlot(self, name, width=6, height=4.5): timestamps = [] sentiment = [] tweets = [] for data_point in self.timeSeries: timestamps.append(datetime.strptime(data_point["TIME"], '%Y-%m-%d %H:%M:%S')) sentiment.append(data_point["SENTIMENT"]) tweets.append(data_point["TWEETS"]) # Plot setup ax1 = plt.figure(figsize=(width, height)).add_subplot(111) ax1.spines["top"].set_visible(False) ax1.get_xaxis().tick_bottom() ax1.get_yaxis().tick_left() ax1.xaxis.set_major_formatter(DateFormatter('%m-%d %H:%M')) lns1 = ax1.plot(timestamps, sentiment, color="dimgrey", lw=0.75, label="Sentiment") plt.yticks(fontsize=8) plt.ylim(ymin=-1, ymax=1) plt.xticks(rotation=50, fontsize=8) ax2 = ax1.twinx() lns2 = ax2.plot(timestamps, tweets, color="dodgerblue", lw=0.5, label="Tweets") ax2.margins(0.05) plt.yticks(fontsize=8) # Labeling ax1.legend(lns1+lns2, ['Sentiment', 'Tweets'], loc=0, frameon=False, fontsize=6) ax1.set_ylabel("Sentiment", weight="light", rotation=90, fontsize=9, labelpad=1) ax2.set_ylabel("Tweets", weight="light", rotation=-90, fontsize=9, labelpad=15) plt.title("Tweet Sentiment", weight ="light", fontsize=12, y=1.08) plt.ylim(ymin=0) plt.tight_layout() file_name = join(BASE_PATH, "outputs", name+".png") plt.savefig(file_name) print("Saved plot {}".format(file_name))
def showPlot(self): timestamps = [] sentiment = [] tweets = [] for data_point in self.timeSeries: timestamps.append(datetime.strptime(data_point["TIME"], '%Y-%m-%d %H:%M:%S')) sentiment.append(data_point["SENTIMENT"]) tweets.append(data_point["TWEETS"]) # Plot setup ax1 = plt.figure(figsize=(6, 4.5)).add_subplot(111) ax1.spines["top"].set_visible(False) ax1.get_xaxis().tick_bottom() ax1.get_yaxis().tick_left() ax1.xaxis.set_major_formatter(DateFormatter('%m-%d %H:%M')) lns1 = ax1.plot(timestamps, sentiment, color="dimgrey", lw=0.75, label="Sentiment") plt.yticks(fontsize=8) plt.ylim(ymin=-1, ymax=1) plt.xticks(rotation=50, fontsize=8) ax2 = ax1.twinx() lns2 = ax2.plot(timestamps, tweets, color="dodgerblue", lw=0.5, label="Tweets") ax2.margins(0.05) plt.yticks(fontsize=8) # Labeling ax1.legend(lns1+lns2, ['Sentiment', 'Tweets'], loc=0, frameon=False, fontsize=6) ax1.set_ylabel("Sentiment", weight="light", rotation=90, fontsize=9, labelpad=1) ax2.set_ylabel("Tweets", weight="light", rotation=-90, fontsize=9, labelpad=15) plt.title("Tweet Sentiment", weight ="light", fontsize=12, y=1.08) plt.ylim(ymin=0) plt.tight_layout() plt.show()
def plotjoins(self, ctx): """Plots the joindates of everyone in the server""" sm = ctx.message.server.members x = sorted([m.joined_at for m in sm]) y = range(len(x)) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y')) plt.plot(x, y) plt.gcf().autofmt_xdate() plt.title("Plot of joins from {}".format(ctx.message.server.name)) buf = BytesIO() plt.savefig(buf, format='png') buf.seek(0) await self.bot.upload(buf, filename='plot.png') buf.close() plt.close()
def plot_date_axis(axes): from matplotlib import dates date_fmt = dates.DateFormatter('%d/%b') hour_fmt = dates.DateFormatter('%H:%M') # TODO: set xaxis minor interval dynamically axes.xaxis.set_major_locator(dates.DayLocator(interval=1)) axes.xaxis.set_major_formatter(date_fmt) # less than 5 days and interval of 3 is okay axes.xaxis.set_minor_locator(dates.HourLocator(interval=4)) axes.xaxis.set_minor_formatter(hour_fmt) axes.xaxis.set_tick_params(which='major', pad=15)
def __init__(self, sessions, context, time_skew=pd.Timedelta('0s')): global mdates, plt # TODO: Could be cleaner import matplotlib.dates as mdates from matplotlib import pyplot as plt from matplotlib import style self.sessions = sessions self.time_skew = time_skew self._last_emit = None self._before_trading_start_bar_yielded = True self.context = context self.fmt = mdates.DateFormatter('%Y-%m-%d %H:%M') style.use('dark_background') fig = plt.figure() fig.canvas.set_window_title('Enigma Catalyst: {}'.format( self.context.algo_namespace)) self.ax_pnl = fig.add_subplot(311) self.ax_custom_signals = fig.add_subplot(312, sharex=self.ax_pnl) self.ax_exposure = fig.add_subplot(313, sharex=self.ax_pnl) if len(context.minute_stats) > 0: self.draw_pnl() self.draw_custom_signals() self.draw_exposure() # rotates and right aligns the x labels, and moves the bottom of the # axes up to make room for them fig.autofmt_xdate() fig.subplots_adjust(hspace=0.5) plt.tight_layout() plt.ion() plt.show()
def graph_log_data(self, destlog): """draw a graph of pi GPU CPU from logdata""" #define lists to hold data from logfile timelist = [] cpulist = [] gpulist = [] #get data from file and put into lists mypath = destlog + "/" + "log.txt" if os.path.isfile(mypath): with open(mypath, 'r') as myfile: for line in myfile: if "TS" in line: timelist.append(line[5:-1]) if "CPU" in line: cpulist.append(line[18:20]) if "GPU" in line: gpulist.append(line[18:20]) else: print("Log file not found at {}".format(mypath)) return 1 #parse dates format mydates = [dateutil.parser.parse(s) for s in timelist] #make graph matplotlib from logfile plt.xticks(rotation=25) plt.subplots_adjust(bottom=0.2) axisx = plt.gca() axisx.set_xticks(mydates) xfmt = md.DateFormatter('%m/%d %H:%M') axisx.xaxis.set_major_formatter(xfmt) axisx.xaxis.label.set_color('red') axisx.yaxis.label.set_color('red') plt.plot(mydates, cpulist, label='CPU', color='green', marker='x') plt.plot(mydates, gpulist, label='GPU', marker='*') plt.xlabel('Date time stamp (DD-MM HH:MM)') plt.ylabel('Temperature (degrees)') plt.title('ARM CPU and GPU temperature of Raspberry Pi 3', color='green') plt.legend(loc='upper right', fancybox=True, shadow=True) plt.grid(True) plt.show()
def _on_xlim_changed(ax: Axes): ax.get_xaxis().set_major_formatter(DateFormatter('%H:%M:%S'))
def generate_subplots(self, x, *args): def _on_xlims_change(axes): # reset the x-axis format when the plot is resized axes.get_xaxis().set_major_formatter(DateFormatter('%H:%M:%S')) i = 0 numplots = len(args) fig = plt.figure() self.cidclick = fig.canvas.mpl_connect('button_press_event', self.onclick) self.cidrelease = fig.canvas.mpl_connect('button_release_event', self.onrelease) self.cidmotion = fig.canvas.mpl_connect('motion_notify_event', self.onmotion) for arg in args: if i == 0: a = fig.add_subplot(numplots, 1, i+1) else: a = fig.add_subplot(numplots, 1, i+1, sharex=self.axes[0]) a.plot(x.to_pydatetime(), arg) a.fmt_xdata = DateFormatter('%H:%M:%S') a.grid(True) a.callbacks.connect('xlim_changed', _on_xlims_change) self.axes.append(a) i += 1 if not mpl.is_interactive(): fig.show() self.figure = fig plt.show() # TO DO: Consider PatchCollection for rectangles.
def plot_price_series(df, ts_lab1, ts_lab2): #months = mdates.MonthLocator() # every month fig, ax = plt.subplots() ax.plot(df.index, df[ts_lab1], label=ts_lab1) ax.plot(df.index, df[ts_lab2], label=ts_lab2) #ax.xaxis.set_major_locator(months) #ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) ax.grid(True) fig.autofmt_xdate() plt.xlabel('Month/Year') plt.ylabel('Price ($)') plt.title('%s and %s Daily Prices' % (ts_lab1, ts_lab2)) plt.legend() plt.show()
def plot_series(ts): #months = mdates.MonthLocator() # every month fig, ax = plt.subplots() ax.plot(ts.index, ts, label=ts.name) #ax.xaxis.set_major_locator(months) #ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) #ax.set_xlim(datetime.datetime(2012, 1, 1), datetime.datetime(2013, 1, 1)) ax.grid(True) fig.autofmt_xdate() plt.xlabel('Month/Year') plt.ylabel('Price ($)') plt.title('Residual Plot') plt.legend() plt.plot(ts) plt.show()
def plot_date_line_and_vline( line_values, line_dates, vline_dates = [], line_label = [], line_color = []): ''' line_values could be 1d or nd arrays ''' if len(line_label) == 0: if len(line_values.shape) == 1: line_label = ['line'] else: line_label_coll = ['line1', 'line2', 'line3', 'line4', 'line5', 'line6', 'line7', 'line8'] line_label = line_label_coll[0:line_values.shape[1]] if len(line_color) == 0: if len(line_values.shape) == 1: line_color = ['CornflowerBlue'] else: line_color_coll = ['Blue', 'Green', 'Red', 'DarkTurquoise', 'Chocolate', 'CadetBlue', 'IndianRed', 'Orange'] line_color = line_color_coll[0:line_values.shape[1]] line_dtdates = [get_datetime_date(x) for x in line_dates] vline_dtdates = [get_datetime_date(x) for x in vline_dates] (fig, ax) = plt.subplots() if len(line_values.shape) == 1: ax.plot_date(line_dtdates, line_values, '-', label = line_label[0], color = line_color[0]) else: for i in xrange(line_values.shape[1]): ax.plot_date(line_dtdates, line_values[:, i], '-', label = line_label[i], color = line_color[i]) for vldate in vline_dtdates: ax.axvline(vldate) ax.xaxis.set_major_formatter(plt_dates.DateFormatter('%Y-%m-%d')) def ydata(y): return '$%1.2f'%y ax.fmt_xdata = plt_dates.DateFormatter('%Y-%m-%d') ax.fmt_ydata = ydata ax.grid(True) # show fig.autofmt_xdate() plt.legend() plt.show()
def gData(stock): stockFile=stock+".txt" date,closep,highp,lowp,openp,volume= np.loadtxt(stockFile,delimiter=',',unpack=True,converters={0: mdates.strpdate2num('%Y%m%d')}) fig=plt.figure() ax1=plt.subplot(1,1,1) # how much by how much by ax1.plot(date,openp) ax1.plot(date,highp) ax1.plot(date,lowp) ax1.plot(date,closep) ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) #max10days ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) plt.show()
def graphData(stock): stockFile=stock+".txt" date,closep,highp,lowp,openp,volume= np.loadtxt(stockFile,delimiter=',',unpack=True, converters={0: mdates.strpdate2num('%Y%m%d')}) fig=plt.figure() ax1=plt.subplot(1,1,1) # how much by how much by ax1.plot(date,openp) ax1.plot(date,highp) ax1.plot(date,lowp) ax1.plot(date,closep) #pretty it up ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) #max10days ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # rotate for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) plt.show()
def main(): array_metrics=get_array_kpi() perfdatalist=array_metrics.get('perf_data') hostiolist = [] dtstimelist = [] readresponselist =[] print (perfdatalist) for perf_host in perfdatalist: hostiolist.append(perf_host.get('HostIOs')) readresponselist.append(perf_host.get('ReadResponseTime')) epochtime=(perf_host.get ('timestamp')) dtstime = round(epochtime/1000) dtstimelist.append(dtstime) dateconv=np.vectorize(dt.datetime.fromtimestamp) convtimelist =(dateconv(dtstimelist)) # print(convtimelist) fig, ax = plt.subplots(1) fig.autofmt_xdate() xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S') ax.xaxis.set_major_formatter(xfmt) plt.plot_date(convtimelist,hostiolist,'-') plt.plot_date(convtimelist, readresponselist, '-') plt.legend(['HostIOs', 'ReadResponseTime'], loc='upper left') plt.subplots_adjust(bottom=0.1) plt.xticks(rotation=25) plt.ylabel('Host IOs') plt.xlabel('Time') plt.title('Host IOs and Read Response times over the last Hour') plt.show()
def plot_single_instrument(ax, instrument_name, t, min_pa, max_pa): min_pa = np.array(min_pa) max_pa = np.array(max_pa) t = np.array(t) if np.any(min_pa > max_pa): minpa_lt_maxpa = min_pa < max_pa minpa_gt_maxpa = min_pa > max_pa max_pa_upper = np.copy(max_pa) min_pa_upper = np.copy(min_pa) max_pa_upper[minpa_gt_maxpa] = 360 max_pa_upper[minpa_lt_maxpa] = np.nan min_pa_upper[minpa_lt_maxpa] = np.nan max_pa_lower = np.copy(max_pa) min_pa_lower = np.copy(min_pa) min_pa_lower[minpa_gt_maxpa] = 0 max_pa_lower[minpa_lt_maxpa] = np.nan min_pa_lower[minpa_lt_maxpa] = np.nan max_pa[minpa_gt_maxpa] = np.nan min_pa[minpa_gt_maxpa] = np.nan ax.fill_between(t, min_pa_upper, max_pa_upper, facecolor='.7', edgecolor='.7', lw=2) ax.fill_between(t, min_pa_lower, max_pa_lower, facecolor='.7', edgecolor='.7', lw=2) ax.fill_between(t, min_pa, max_pa, edgecolor='.7', facecolor='.7', lw=2) ax.set_ylabel("Available Position Angle (Degree)") ax.set_title(instrument_name) ax.fmt_xdata = DateFormatter('%Y-%m-%d') else: ax.fill_between(t, min_pa, max_pa, edgecolor='none', facecolor='.7') ax.set_ylabel("Available Position Angle (Degree)") ax.set_title(instrument_name) ax.fmt_xdata = DateFormatter('%Y-%m-%d')
def make_date_ticks(ax, fs=12): from matplotlib.dates import YearLocator, MonthLocator, DateFormatter years = YearLocator() months = MonthLocator(range(1, 13), bymonthday=1, interval=2) yearsFmt = DateFormatter('%Y') monthsFmt = DateFormatter("%b") ax.tick_params(axis='x', which='major', labelsize=fs, pad=20) ax.tick_params(axis='x', which='minor', pad=7) ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.xaxis.set_minor_locator(months) ax.xaxis.set_minor_formatter(monthsFmt)
def graph_all_miq_workers(graph_file_path, process_results, provider_names): starttime = time.time() file_name = graph_file_path.join('all-processes.png') fig, ax = plt.subplots() plt.title('Provider(s): {}\nAll Workers/Monitored Processes'.format(provider_names)) plt.xlabel('Date / Time') plt.ylabel('Memory (MiB)') for process_name in process_results: if 'Worker' in process_name or 'Handler' in process_name or 'Catcher' in process_name: for process_pid in process_results[process_name]: dates = process_results[process_name][process_pid].keys() rss_samples = list(process_results[process_name][process_pid][ts]['rss'] for ts in process_results[process_name][process_pid].keys()) vss_samples = list(process_results[process_name][process_pid][ts]['vss'] for ts in process_results[process_name][process_pid].keys()) plt.plot(dates, rss_samples, linewidth=1, label='{} {} RSS'.format(process_pid, process_name)) plt.plot(dates, vss_samples, linewidth=1, label='{} {} VSS'.format( process_pid, process_name)) dateFmt = mdates.DateFormatter('%m-%d %H-%M') ax.xaxis.set_major_formatter(dateFmt) ax.grid(True) plt.legend(loc='upper center', bbox_to_anchor=(1.2, 0.1), fancybox=True) fig.autofmt_xdate() plt.savefig(str(file_name), bbox_inches='tight') plt.close() timediff = time.time() - starttime logger.info('Plotted All Type/Process Memory in: {}'.format(timediff))
def plot_daily_inf_res(df, symbols=[], plot_top=0): df = df.copy() # data_nasdaq_top_100_preprocessed_merge.groupby('SYMBOL') years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month years_fmt = mdates.DateFormatter('%Y') df['max_pmi_is'] = df[[col for col in df.columns if 'pmi_is' in col]].max(axis=1) if len(symbols) > 0: df = df.loc[symbols] if plot_top > 0: idx = df.groupby('SYMBOL')['max_pmi_is'].max().sort_values(ascending=False).index[:plot_top].values print idx df = df.loc[list(idx)] # df = df.reindex(index=idx) fig, ax = plt.subplots(figsize=(15,5)) for key, grp in df.groupby('SYMBOL'): print "key", key # grp.reset_index() # print grp.DATE ax.plot(grp.DATE.reset_index(drop=True), grp['max_pmi_is'], label=key) # grp['D'] = pd.rolling_mean(grp['B'], window=5) # plt.plot(grp['D'], label='rolling ({k})'.format(k=key)) # datemin = (df.DATE.min().year) # datemax = (df.DATE.max().year + 1) # print datemin, datemax # ax.set_xlim(datemin, datemax) ax.set_ylim(0, 500) plt.legend(loc='best') plt.ylabel('PMI IS (-2)') fig.autofmt_xdate() plt.show()
def plot_trigger_criterion(transient): fig, ax = plt.subplots(1) # rotate and align the tick labels so they look better for i in range(len(transient.trigger_criterion)): ax.plot(transient.trigger_criterion_timestamps[i], transient.trigger_criterion[i], '.') import matplotlib.dates as mdates ax.fmt_xdata = mdates.DateFormatter('%H:%M:%S') fig.autofmt_xdate() return fig
def generateActivityInfoForGroup(self, groupName): timestampNow = int(time()) timestampYesterday = timestampNow - self.timestampSubtract records = list(self.coll.find({ 'to': groupName, 'timestamp': { '$gt': timestampYesterday } }).sort([ ('timestamp', DESCENDING) ])) fn = self.generateTmpFileName() # Get histogram for activity hist, bins = np.histogram([ x['timestamp'] for x in records ], bins=24) center = (bins[:-1] + bins[1:]) / 2 datex = [ datetime.fromtimestamp(x) for x in center ] pp.figure(figsize=(6,14)) ax = pp.subplot(2, 1, 1) pp.plot_date(datex, hist, '.-') pp.gcf().autofmt_xdate() pp.xlabel(u'??????', fontproperties=self.prop) pp.ylabel(u'??????', fontproperties=self.prop) ax.xaxis.set_major_formatter(DateFormatter('%m-%d %H:%M')) # Get bar chart for active users pieDat = Counter([ x['from'] for x in records ]) pieDatSorted = sorted([ (k, pieDat[k]) for k in pieDat ],key=lambda x: x[1], reverse=True) if len(pieDatSorted) > self.maxActivityInfoCount: pieDatSorted = pieDatSorted[:self.maxActivityInfoCount] ax = pp.subplot(2, 1, 2) width = 0.7 x = np.arange(len(pieDatSorted)) + width xText = [ xx[0] for xx in pieDatSorted ] y = [ xx[1] for xx in pieDatSorted ] pp.bar(x, y, width) a = pp.gca() a.set_xticklabels(a.get_xticks(), { 'fontProperties': self.prop }) pp.xticks(x, xText, rotation='vertical') pp.xlabel(u'??', fontproperties=self.prop) pp.ylabel(u'24?????', fontproperties=self.prop) ax.set_xlim([ 0, len(xText) + 1 - width ]) pp.margins(0.2) pp.savefig(fn) return fn
def plotDatePrice(productID, productTitle, data): # Data setup x, y = [], [] for datapoint in data: date = datapoint.split('|')[0] price = float(datapoint.split('|')[1]) x.append(dt.datetime.strptime(date, '%Y-%m-%d')) y.append(price) x = matplotlib.dates.date2num(x) x_np, y_np = np.array(x), np.array(y) # Plot setup ax = plt.figure(figsize=(6, 3)).add_subplot(111) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() ax.plot(x_np, y_np, color='lightblue', lw=2) ax.margins(0.05) ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: ('$%i' % (x)))) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) plt.yticks(fontsize=8) plt.ylim(ymin=min(y)*0.7, ymax=max(y)*1.3) plt.title('Recent Price History\n'+productTitle, weight ='light', fontsize=12, y=1.08) plt.xticks(rotation=40, fontsize=7) plt.tight_layout() plt.savefig(productID+'.png') return productID+'.png' # ----- Email Configuration ----------------------------------------------------
def plot_heart(day): beats = session.query(models.Heart).filter( and_( Extract('day', models.Heart.date) == Extract('day', day), Extract('month', models.Heart.date) == Extract('month', day), Extract('year', models.Heart.date) == Extract('year', day), )).all() if not beats: print("No data to plot.") return dates_x = [elem.date for elem in beats] beats_y = [elem.value for elem in beats] dates_x_less = [elem for index, elem in enumerate(dates_x) if index%10==0] beats_y_less = [elem for index, elem in enumerate(beats_y) if index%10==0] fig = plt.figure(figsize=(28, 5), dpi = 400, edgecolor='k') ax = fig.add_subplot(111) ax.set_xticks(dates_x_less) ax.xaxis.grid(True) ax.yaxis.grid(True) xfmt = md.DateFormatter('%H:%M') ax.xaxis.set_major_formatter(xfmt) current_date = day.strftime("%B %d, %Y") plt.suptitle(current_date, fontsize=20) plt.xlabel('Time', fontsize=18) plt.ylabel('Heart rate (BPM)', fontsize=16) plt.subplots_adjust(bottom=0.2) plt.xticks(rotation=90) plt.plot(dates_x_less, beats_y_less, "o-") plt.savefig(day.strftime("%Y-%m-%d")+'_heart.png', dpi=400, bbox_inches='tight') #plt.show() plt.clf() plt.cla() # clear axis del fig
def plot_weight(): weight = session.query(models.Weight).order_by(desc(models.Weight.date)).\ filter().all() if not weight: print("No data to plot.") return dates_x = [elem.date for elem in weight] weight_y = [elem.value for elem in weight] fig = plt.figure(figsize=(40, 5), dpi = 400, edgecolor='k') ax = fig.add_subplot(111) ax.set_xticks(dates_x) ax.xaxis.grid(True) ax.yaxis.grid(True) xfmt = md.DateFormatter('%d-%m-%Y') ax.xaxis.set_major_formatter(xfmt) plt.suptitle("Weight evolution", fontsize=20) plt.xlabel('Time', fontsize=18) plt.ylabel('Weight (kg)', fontsize=16) plt.subplots_adjust(bottom=0.2) plt.xticks(rotation=90) plt.plot(dates_x, weight_y, "o-") plt.savefig('weight.png', dpi=400, bbox_inches='tight') #plt.show() plt.clf() plt.cla() # clear axis del fig
def matplotlib_locator_formatter(timedelta, span=1): """ Compute appropriate locator and formatter for renderers based on matplotlib, depending on designated time span. """ from matplotlib.dates import date_ticker_factory, DateFormatter locator, formatter = date_ticker_factory(span) # http://pandas.pydata.org/pandas-docs/stable/timedeltas.html # https://stackoverflow.com/questions/16103238/pandas-timedelta-in-days is_macro = timedelta <= Timedelta(days=1) is_supermacro = timedelta <= Timedelta(minutes=5) if is_macro: #formatter = DateFormatter(fmt='%H:%M:%S.%f') formatter = DateFormatter(fmt='%H:%M') if is_supermacro: formatter = DateFormatter(fmt='%H:%M:%S') # Formatter overrides #if formatter.fmt == '%H:%M\n%b %d': # formatter = DateFormatter(fmt='%Y-%m-%d %H:%M') # Labs #from matplotlib.dates import AutoDateLocator, AutoDateFormatter, HOURLY #locator = AutoDateLocator(maxticks=7) #locator.autoscale() #locator.intervald[HOURLY] = [5] #formatter = AutoDateFormatter(breaks) #formatter = date_format('%Y-%m-%d\n%H:%M') # Default building blocks #from matplotlib.dates import AutoDateFormatter, AutoDateLocator #locator = AutoDateLocator() #formatter = AutoDateFormatter(locator) return locator, formatter
def plot_supply(request): from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter currency = request.GET['currency'] genesis = crypto_data[currency.lower()]['genesis_date'] currency_name = crypto_data[currency.lower()]['name'] s = SupplyEstimator(currency) try: max_block = crypto_data[currency.lower()]['supply_data']['reward_ends_at_block'] end = s.estimate_date_from_height(max_block) except KeyError: end = genesis + datetime.timedelta(days=365 * 50) x = list(date_generator(genesis, end)) y = [s.calculate_supply(at_time=z)/1e6 for z in x] fig = Figure() ax = fig.add_subplot(111) ax.plot_date(x, y, '-') ax.set_title("%s Supply" % currency_name) ax.grid(True) ax.xaxis.set_label_text("Date") ax.yaxis.set_label_text("%s Units (In millions)" % currency.upper()) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas = FigureCanvas(fig) response = http.HttpResponse(content_type='image/png') canvas.print_png(response) return response
def apply_date_formatting_to_axis(ax): """ Format x-axis of input plot to a readable date format """ ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(0), interval=1)) ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a')) ax.xaxis.grid(True, which="minor") ax.yaxis.grid() ax.xaxis.set_major_locator(dates.MonthLocator()) ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y')) return ax
def clear(self): self.graph.cla() zero = dt.datetime.fromtimestamp(0) one = dt.datetime.fromtimestamp(1) x, y = [zero, one], [-1, -1] self.graph.set_xlim(zero, one) self.graph.set_ylim(0, 1) self.power_line, = self.graph.plot(x, y, color='red') self.graph.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d %H:%M:%S")) self.graph.xaxis.set_major_locator(LinearLocator(numticks=6)) plt.setp(self.graph.get_xticklabels(), rotation=10) self.graph.set_ylabel("Power (kW)")
def showPlot(date, data, file_name): import matplotlib.ticker as mticker import matplotlib.dates as mdates import datetime fig, ax = plt.subplots() ax.xaxis.set_major_locator(mticker.MaxNLocator(5)) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) print(date) # print(data) # date = [datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1, 1, 2, 0, 0), datetime.datetime(1, 1, 3, 0, 0), datetime.datetime(1, 1, 4, 0, 0)] # data = [1, 2, 3, 4] ax.plot(date, data) # fig.plot([1, 2, 3], [1, 1, 1]) fig.savefig(file_name) plt.close(fig) # def showPlotMix(data, file_name='test.png'): # fig, arr = plt.subplots(nrows=len(data), sharex=True) # print('showPlotMix') # for i, d in enumerate(data): # # print(len(d[0])) # for j, td in enumerate(d[0]): # # print(len(td)) # print(len(d[1][j])) # arr[i].plot(d[1][j], td) # fig.savefig(file_name) # plt.close(fig)
def showPlotMixSeparate(data, date, file_name='test.png'): print('shopPlotMixSeparate') import matplotlib.ticker as mticker import matplotlib.dates as mdates fig, arr = plt.subplots() ax1 = arr ax1.xaxis.set_major_locator(mticker.MaxNLocator(5)) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) for j, td in enumerate(date): arr.plot(td, data[j]) fig.savefig(file_name) plt.close(fig)
def showPlotCompare(data, date, file_name): print("showPlotCompare") print(len(date)) import matplotlib.ticker as mticker import matplotlib.dates as mdates fig, arr = plt.subplots(nrows=len(data), sharex=True) for i, d in enumerate(data): arr[i].xaxis.set_major_locator(mticker.MaxNLocator(7)) arr[i].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) # fig.suptitle('test title', fontsize=20) # arr[i].set_title('ax1 title') arr[i].plot(date, d) fig.savefig(file_name) plt.close(fig)
def showPlotLabelsCompare(data, date, labels, file_name): print("showPlotCompare") print(len(date)) import matplotlib.ticker as mticker import matplotlib.dates as mdates fig, arr = plt.subplots(nrows=len(data), sharex=True) for i, d in enumerate(data): arr[i].xaxis.set_major_locator(mticker.MaxNLocator(7)) arr[i].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) # fig.suptitle('test title', fontsize=20) arr[i].set_title(labels[i]) arr[i].plot(date, d) fig.savefig(file_name) plt.close(fig)
def showPlotCompareSeparate(data, date, file_name): print("showPlotCompare") print(len(date)) import matplotlib.ticker as mticker import matplotlib.dates as mdates fig, arr = plt.subplots(nrows=len(data), sharex=True) for i, d in enumerate(data): arr[i].xaxis.set_major_locator(mticker.MaxNLocator(7)) arr[i].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) arr[i].plot(date[i], d) fig.savefig(file_name) plt.close(fig)
def chartFormatAxisX(self, ax, k_dict, p_dict): """""" ax.tick_params(axis='x', **k_dict['k_major_x']) ax.tick_params(axis='x', **k_dict['k_minor_x']) ax.xaxis.set_major_formatter(mdate.DateFormatter(p_dict['xAxisLabelFormat'])) self.setAxisScaleX(p_dict['xAxisBins']) # Set the scale for the X axis. We assume a date. return ax
def set_date_axis(ax=None, dateformat='%d.%m.'): """Set DateFormatter for given AxesSubplot. Parameters: ax (AxesSubplot): Matplotlib axes. dateformat (str): Format string for date labels on xaxis. """ if ax is None: ax = plt.gca() formatter = dates.DateFormatter(dateformat) ax.xaxis.set_major_formatter(formatter) ax.grid('on', which='both', linestyle='-')