def __init__(self, parent=None, tp=1, trade_interval=60): super(figure, self).__init__(parent) self.type = tp figure.fig_num += 1 self.fig_num = figure.fig_num self.title = '' self.sid = '' self.init_figure() self.interval = del2num(trade_interval) self.canvas1 = figureCanvas(self.figure1) self.canvas1.draw() self.layout = QHBoxLayout(self) self.layout.addWidget(self.canvas1) if self.type != figure.CDF_PLOT: if trade_interval < 60: self.xlocater = SecondLocator(bysecond=range(0, 60, trade_interval)) self.xformatter = DateFormatter("%H:%M:%S") else: self.xlocater = MinuteLocator(byminute=range(0, 60, trade_interval / 60)) self.xformatter = DateFormatter("%H:%M") else: if trade_interval < 5: self.xlocater = SecondLocator(bysecond=range(0, 60, 12 * trade_interval)) self.xformatter = DateFormatter("%H:%M:%S") else: self.xlocater = MinuteLocator(byminute=range(0, 60, trade_interval / 5)) self.xformatter = DateFormatter("%H:%M")
def plot_traces(sts, labels, title): """ This function plot streams of seismic signals. Several streams can be passed to the function for comparison. Input parameters sts: List of N streams (Obspy Stream) labels: List of N labels title: Title of figure """ rc('font', size=12.0) fig, ax = plt.subplots(sts[0].count(), 1, sharex=True, sharey=True, figsize=(10, 12)) ax[0].set_title(title) # Plot each trace of each stream for st, label in zip(sts, labels): for itr, tr in enumerate(st): ilabel = tr.stats.station + '.' + tr.stats.channel[ 2] + ' - ' + label ax[itr].grid('on', which='both') ax[itr].plot(tr.times('matplotlib'), tr.data, label=ilabel) ax[itr].ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) if itr is not 0: ax[itr].yaxis.get_offset_text().set_visible(False) ax[itr].set(ylabel='$v_Z$ (m/s)') ax[itr].legend(loc=1) ax[itr].set(xlabel='Time (s)') # Bring subplots close to each other. fig.subplots_adjust(hspace=0.1) # Hide x labels and tick labels for all but bottom plot. for axi in ax: axi.label_outer() # Format time axis if st[0].stats.npts * st[0].stats.delta > 80: plt.gca().xaxis.set_minor_locator( SecondLocator(bysecond=range(10, 60, 10))) else: plt.gca().xaxis.set_minor_locator( SecondLocator(bysecond=range(5, 60, 5))) plt.gca().xaxis.set_minor_formatter(DateFormatter("%S''")) plt.gca().xaxis.set_major_locator(MinuteLocator(byminute=range(0, 60, 1))) plt.gca().xaxis.set_major_formatter(DateFormatter('%H:%M:%S')) plt.show()
def date_handler(time_data, ax, time_frame): ax.xaxis.set_major_locator(ticker.MaxNLocator(nbins=8)) if time_frame == 'year': ax.xaxis.set_major_formatter(DateFormatter('%Y')) elif time_frame == 'month': ax.xaxis.set_major_locator(MonthLocator(bymonth=range(1, 13), interval=_time_freq(time_data, 8, 30))) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m')) elif time_frame == 'day': ax.xaxis.set_major_locator(DayLocator(bymonthday=range(1, 32), interval=_time_freq(time_data, 8, 1))) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) elif time_frame == 'hour': ax.xaxis.set_major_locator(HourLocator(byhour=range(0, 24, 4))) ax.xaxis.set_major_formatter(DateFormatter('%H:%M')) elif time_frame == 'minute': ax.xaxis.set_major_locator(MinuteLocator(byminute=range(0, 60, 1), interval=60)) ax.xaxis.set_major_formatter(DateFormatter('%H:%M')) elif time_frame == 'second': ax.xaxis.set_major_locator(SecondLocator(bysecond=range(0, 60, 1), interval=10)) ax.xaxis.set_major_formatter(DateFormatter('%M:%S'))
def __init__(self): self.fig = Figure() self.ax = self.fig.add_subplot(111) FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.ax.set_xlabel("time of data generator") self.ax.set_ylabel('random data value') self.ax.legend() self.ax.set_ylim(Y_MIN, Y_MAX) self.ax.xaxis.set_major_locator( MinuteLocator()) # every minute is a major locator self.ax.xaxis.set_minor_locator(SecondLocator( [10, 20, 30, 40, 50])) # every 10 second is a minor locator self.ax.xaxis.set_major_formatter( DateFormatter('%H:%M:%S')) # tick label formatter self.curveObj = None # draw object
def plot(self, datax, datay): if self.curveObj is not None: self.fig.clf() self.ax = self.fig.add_subplot(111) self.fig.suptitle(self.title) # set title self.ax.set_xlabel("time") self.ax.set_ylabel(self.valueName) self.ax.legend() # self.ax.set_ylim(Y_MIN, Y_MAX) self.ax.xaxis.set_major_locator(MinuteLocator()) # every minute is a major locator self.ax.xaxis.set_minor_locator(SecondLocator([5, 10, 15, 20, 25])) # every 10 second is a minor locator self.ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S')) # tick label formatter self.curveObj, = self.ax.plot_date(np.array(datax), np.array(datay), 'bo-') # else: # # update data of draw object # self.curveObj.set_data(np.array(datax), np.array(datay)) # # update limit of X axis,to make sure it can move # self.ax.set_xlim(datax[0], datax[-1]) ticklabels = self.ax.xaxis.get_ticklabels() for tick in ticklabels: tick.set_rotation(25) self.draw()
def __init__(self): self.fig = Figure() self.ax = self.fig.add_subplot( 111, facecolor='#000000') # facecolor设置图表背景颜色(or #FFDAB9) FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) # self.ax.set_xlabel("time of data generator") self.ax.grid(True) # 显示网格 self.ax.set_ylabel('Accuracy') self.ax.legend() self.ax.set_ylim(Y_MIN, Y_MAX) self.ax.xaxis.set_major_locator( MinuteLocator()) # every minute is a major locator self.ax.xaxis.set_minor_locator(SecondLocator( [10, 20, 30, 40, 50])) # every 10 second is a minor locator self.ax.xaxis.set_major_formatter( DateFormatter('%H:%M:%S')) # tick label formatter self.curveObj = None # draw object
def set_time_labels(self, labels, fmt, maj_int, min_int): default = self.axis.get('default') default.xaxis.set_major_locator(MinuteLocator(interval=maj_int)) default.xaxis.set_minor_locator(SecondLocator(interval=min_int)) if len(default.xaxis.get_major_ticks()) < len(labels): labels.pop(0) default.set_xticklabels( [d != ' ' and d.strftime(fmt) or '' for d in labels])
def timeticks(tdiff): """ NOTE do NOT use "interval" or ticks are misaligned! use "bysecond" only! """ if isinstance(tdiff, xarray.DataArray): # len==1 tdiff = timedelta(seconds=tdiff.values / np.timedelta64(1, "s")) assert isinstance(tdiff, timedelta), "expecting datetime.timedelta" if tdiff > timedelta(hours=2): return None, None elif tdiff > timedelta(minutes=20): return MinuteLocator(byminute=range(0, 60, 5)), MinuteLocator( byminute=range(0, 60, 2)) elif (timedelta(minutes=10) < tdiff) & (tdiff <= timedelta(minutes=20)): return MinuteLocator(byminute=range(0, 60, 2)), MinuteLocator( byminute=range(0, 60, 1)) elif (timedelta(minutes=5) < tdiff) & (tdiff <= timedelta(minutes=10)): return MinuteLocator(byminute=range(0, 60, 1)), SecondLocator( bysecond=range(0, 60, 30)) elif (timedelta(minutes=1) < tdiff) & (tdiff <= timedelta(minutes=5)): return SecondLocator(bysecond=range(0, 60, 30)), SecondLocator( bysecond=range(0, 60, 10)) elif (timedelta(seconds=30) < tdiff) & (tdiff <= timedelta(minutes=1)): return SecondLocator(bysecond=range(0, 60, 10)), SecondLocator( bysecond=range(0, 60, 2)) else: return SecondLocator(bysecond=range(0, 60, 2)), SecondLocator( bysecond=range(0, 60, 1))
def timeticks(tdiff: timedelta): assert isinstance(tdiff, timedelta) if tdiff > timedelta(minutes=20): return MinuteLocator(interval=5) elif (timedelta(minutes=1) < tdiff) & (tdiff <= timedelta(minutes=20)): return MinuteLocator(interval=1) else: return SecondLocator(interval=5)
def plot_ts(dsd, varname, date_format="%H:%M", tz=timezone.utc, x_min_tick_format="hour", title=None, ax=None, fig=None, **kwargs): """ Time series plot of variable. Parameters ---------- dsd : dict PyDSD dictionary. varname : str or list Variable name(s) to plot. date_format : str Timestring format characters. tz : str Time zone to uses, see datetime module. x_min_tick_format : str Minor tick formatting, 'second','minute','hour','day' supported title : str ax : Matplotlib Axis instance fig : Matplotlib Figure instance kwkargs : Keyword arguments to pass to pcolormesh """ ax = parse_ax(ax) fig = parse_ax(fig) x_fmt = DateFormatter(date_format, tz=tz) sample_time = [ datetime.datetime.fromtimestamp(i) for i in dsd.time['data'].filled() ] ax.plot_date(sample_time, dsd.fields[varname]["data"], **kwargs) ax.xaxis.set_major_formatter(x_fmt) if x_min_tick_format == "second": ax.xaxis.set_minor_locator(SecondLocator()) elif x_min_tick_format == "minute": ax.xaxis.set_minor_locator(MinuteLocator()) elif x_min_tick_format == "hour": ax.xaxis.set_minor_locator(HourLocator()) elif x_min_tick_format == "day": ax.xaxis.set_minor_locator(DayLocator()) if title is not None: ax.set_title(title) else: plt.title(dsd.fields[varname]['long_name']) plt.ylabel(dsd.fields[varname]['units']) plt.xlabel('Time') return fig, ax
def __init__(self): # 创建一个Figure,注意:该Figure为matplotlib下的.figure,不是matplotlib.pyplot下面的figure self.figure = Figure() FigureCanvas.__init__(self, self.figure) # 初始化父类 FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) self.ax = self.figure.add_subplot( 111) # 创建一个新的 1 * 1 的子图,接下来的图样绘制在其中的第 1 块(也是唯一的一块) self.ax.set_xlabel('Time') # 设置x坐标轴名 self.ax.grid(True) # 为坐标系设置网格 self.ax.xaxis.set_major_locator(SecondLocator([0, 20, 40])) # 主刻度,10s间隔 self.ax.xaxis.set_minor_locator( SecondLocator([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55])) # 次刻度,5s间隔 self.ax.xaxis.set_major_formatter( DateFormatter('%H:%M:%S')) # x坐标主刻度名格式 self.curveObj1 = None # draw object self.curveObj2 = None self.curveObj3 = None
def pickTW(tr): """ This function allows to interactively pick times on the signal. Input parameters tr: Seismic signal (Obspy Trace) """ rc('font', size=12.0) # Plot seismic trace fig = plt.figure(figsize=(10,4)) ax = fig.add_subplot(111) title = ('Successively select start and end time of signal with right mouse button.') label = tr.stats.station+'.'+tr.stats.channel[2] ax.set_title(title) ax.grid() ax.plot(tr.times('matplotlib'), tr.data,label=label) ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) ax.legend(loc=1) ax.set_xlabel('Time (s)') ax.set_ylabel('$v_Z$ (m/s)') # Format time axis if tr.stats.npts*tr.stats.delta > 80 : plt.gca().xaxis.set_minor_locator( SecondLocator(bysecond=range(10,60,10)) ) else: plt.gca().xaxis.set_minor_locator( SecondLocator(bysecond=range( 5,60, 5)) ) plt.gca().xaxis.set_minor_formatter( DateFormatter("%S''") ) plt.gca().xaxis.set_major_locator( MinuteLocator(byminute=range( 0,60, 1)) ) plt.gca().xaxis.set_major_formatter( DateFormatter('%H:%M:%S') ) # Start picking cid = fig.canvas.mpl_connect('button_press_event', onclick) plt.show() return()
def timelbl(time, ax, tctime): """improve time axis labeling""" if time.size < 200: ax.xaxis.set_minor_locator(SecondLocator(interval=10)) ax.xaxis.set_minor_locator(SecondLocator(interval=2)) elif time.size < 500: ax.xaxis.set_minor_locator(MinuteLocator(interval=10)) ax.xaxis.set_minor_locator(MinuteLocator(interval=2)) # ax.axvline(tTC[tReqInd], color='white', linestyle='--',label='Req. Time') if (tctime["tstartPrecip"] >= time[0]) & (tctime["tstartPrecip"] <= time[-1]): ax.axvline(tctime["tstartPrecip"], color="red", linestyle="--", label="Precip. Start") if (tctime["tendPrecip"] >= time[0]) & (tctime["tendPrecip"] <= time[-1]): ax.axvline(tctime["tendPrecip"], color="red", linestyle="--", label="Precip. End")
def plot_trace(tr, event): """ This function plots a single seismic trace. Input parameters tr: Seismic signal (Obspy Trace) """ rc('font', size=12.0) fig = plt.figure(figsize=(10,4)) ax = fig.add_subplot(111) ax.set_title('Seismic signal and picked time window (red dashed lines)') # Plot each trace of each stream label = tr.stats.station+'.'+tr.stats.channel[2] ax.grid(which='both') ax.plot(tr.times('matplotlib'), tr.data, lw=0.8, label=label) ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) if os.path.isfile('pickedTW_'+event+'.txt'): pickTW = np.loadtxt('pickedTW_'+event+'.txt') ax.axvline(pickTW[0],color='C3',linestyle='--') ax.axvline(pickTW[1],color='C3',linestyle='--') ax.legend(loc=1) ax.set_xlabel('Time (s)') ax.set_ylabel('$v_Z$ (m/s)') # Format time axis if tr.stats.npts*tr.stats.delta > 80 : plt.gca().xaxis.set_minor_locator( SecondLocator(bysecond=range(10,60,10)) ) else: plt.gca().xaxis.set_minor_locator( SecondLocator(bysecond=range( 5,60, 5)) ) plt.gca().xaxis.set_minor_formatter( DateFormatter("%S''") ) plt.gca().xaxis.set_major_locator( MinuteLocator(byminute=range( 0,60, 1)) ) plt.gca().xaxis.set_major_formatter( DateFormatter('%H:%M:%S') ) plt.show()
def plotTimes(group_id, data): formatter = DateFormatter('%m-%d-%y') x = data["x"] y = data["y"] _, axes = plt.subplots(1, data["years"], sharey=True) if len(data['boundaries']) == 0: sendMessage(group_id, text=f'{data["name"]} has no 5k races recorded.') return False if data["years"] == 1: axes = [axes] if DEBUG: print(f'Starting plot for {data["name"]}... ',end='') for i in range(data['years']): axes[i].plot(x, y) if i < data['years'] - 1: axes[i].spines['right'].set_visible(False) if i > 0: axes[i].spines['left'].set_visible(False) axes[i].yaxis.set_ticks_position('none') axes[i].set_xlim(data['boundaries'][i]['start'],data['boundaries'][i]['end']) plt.sca(axes[i]) plt.xticks(rotation=65) plt.rc('axes', labelsize=8) axes[i].xaxis.set_major_formatter(formatter) axes[i].grid(linestyle="dashed",linewidth=0.5) loc = SecondLocator(interval=15) axes[i].yaxis.set_major_locator(loc) axes[i].yaxis.set_major_formatter(DateFormatter('%M:%S')) for label in (axes[i].get_xticklabels()): label.set_fontsize(7) #axes[i].get_xticklabels().set_fontsize(10) if DEBUG: print('done.') try: plt.sca(axes[0]) except IndexError: sendMessage(group_id, text=f"{data['name']} has no times recorded.") return False plt.xlabel('Date') plt.ylabel('5k Time') plt.sca(axes[int(data['years']/2)]) plt.title(data['name']) if DEBUG: print('Try to save figure... ',end='') plt.savefig('plot.png', format="png") plt.close() if DEBUG: print('done.') return True
def plotTimeline(a, filename): # Converts str into a datetime object. conv = lambda s: dt.datetime.strptime(s, '%H:%M:%S:%f') # Use numpy to read the data in. data = np.genfromtxt(a, converters={1: conv, 2: conv}, \ names=['caption', 'start', 'stop', 'state'], \ dtype=None, delimiter=",") cap, start, stop = data['caption'], data['start'], data['stop'] # Check the status, because we paint all lines with the same color # together is_ok = (data['state'] == 'OK') not_ok = np.logical_not(is_ok) # Get unique captions and there indices and the inverse mapping captions, unique_idx, caption_inv = np.unique(cap, 1, 1) # Build y values from the number of unique captions. y = (caption_inv + 1) / float(len(captions) + 1) # Plot ok tl black timelines(y[is_ok], start[is_ok], stop[is_ok], 'k') # Plot fail tl red timelines(y[not_ok], start[not_ok], stop[not_ok], 'r') # Setup the plot ax = plt.gca() fig = ax.get_figure() fig.set_figheight(6) fig.set_figwidth(18) ax.xaxis_date() myFmt = DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(myFmt) ax.xaxis.set_major_locator( SecondLocator(interval=10)) # used to be SecondLocator(0, interval=20) plt.axhspan(0.19, 1, facecolor='0.8', alpha=0.5) # To adjust the xlimits a timedelta is needed. delta = (stop.max() - start.min()) / 10 plt.yticks(y[unique_idx], captions, size=14) # plt.ylim(0,1) plt.tight_layout() plt.gcf().subplots_adjust(bottom=0.1) plt.xticks(size=14) plt.xlim(start.min() - delta, stop.max() + delta) plt.xlabel('Timeline', size=17) plt.savefig(filename, format='eps', dpi=200)
def plot_timeSeries(x, y): days = DayLocator() hours = HourLocator() minutes = MinuteLocator() seconds = SecondLocator() ax = plt.subplot(111) plt.xticks(rotation=45) ax.xaxis.set_major_locator(days) ax.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d')) # ax.xaxis.set_minor_locator(hours) # ax.xaxis.set_minor_formatter(mdate.DateFormatter('%H')) plt.plot(x, y) plt.show()
def plot_ts(dsd, varname, date_format='%H:%M', tz=None, x_min_tick_format='minute', title=None, ax=None, fig=None, **kwargs): """ Time series plot of variable. Parameters ---------- dsd : dict PyDSD dictionary. varname : str or list Variable name(s) to plot. date_format : str Timestring format characters. tz : str Time zone to uses, see datetime module. x_min_tick_format : str Minor tick formatting, 'second','minute','hour','day' supported title : str ax : Matplotlib Axis instance fig : Matplotlib Figure instance kwkargs : Keyword arguments to pass to pcolormesh """ ax = parse_ax(ax) fig = parse_ax(fig) x_fmt = DateFormatter(date_format, tz=tz) ax.plot_date(dsd.time['data'], dsd.fields[varname]['data'], **kwargs) ax.xaxis.set_major_formatter(x_fmt) if x_min_tick_format == 'second': ax.xaxis.set_minor_locator(SecondLocator()) elif x_min_tick_format == 'minute': ax.xaxis.set_minor_locator(MinuteLocator()) elif x_min_tick_format == 'hour': ax.xaxis.set_minor_locator(HourLocator()) elif x_min_tick_format == 'day': ax.xaxis.set_minor_locator(DayLocator()) if title is not None: ax.set_title(title) return fig, ax
def live_traffic(): with get_conn() as conn: cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) destination_history_query = """ SELECT * FROM traffic WHERE recorded_at >= now() - INTERVAL '10 minutes'; """ cur.execute(destination_history_query) times = cur.fetchall() fig = Figure(figsize=(30, 8), dpi=80, facecolor='w', edgecolor='k', tight_layout=True) ax = fig.add_subplot(111) begin_times = [row['recorded_at'] for row in times] upload = [row['upload'] for row in times] ax.plot_date(x=begin_times, y=upload, label='upload', linestyle='solid') download = [row['download'] for row in times] ax.plot_date(x=begin_times, y=download, label='download', linestyle='solid') ax.set_xlabel('Time') ax.set_ylabel('Bandwidth') ax.set_ylim(bottom=0) ax.xaxis_date() my_fmt = DateFormatter('%H:%M') ax.xaxis.set_major_formatter(my_fmt) ax.xaxis.set_major_locator(SecondLocator(interval=60)) ax.legend() ax.grid() png_output = io.BytesIO() fig.set_canvas(FigureCanvasAgg(fig)) fig.savefig(png_output, transparent=True, format='png') response = make_response(png_output.getvalue()) response.headers['content-type'] = 'image/png' return response
def plot(start: "np.ndarray[datetime]", stop: "np.ndarray[datetime]", state: "np.ndarray[str]", cap: "np.ndarray[str]"): """Originally based on: https://stackoverflow.com/a/7685336/965332""" # Get unique captions, their indices, and the inverse mapping captions, unique_idx, caption_inv = np.unique(cap, 1, 1) # Build y values from the number of unique captions y = (caption_inv + 1) / float(len(captions) + 1) # Build colors states, _, states_inv = np.unique(state, 1, 1) cmap = plt.get_cmap('tab10') colors = cmap(np.linspace(0, 1, len(states))) # Plot function def timelines(y, xstart, xstop, color): """Plot timelines at y from xstart to xstop with given color.""" plt.hlines(y, same_date(xstart), same_date(xstop), color, lw=12) timelines(y, start, stop, colors[states_inv]) # Setup the plot plt.title("Timeline") ax = plt.gca() # Create the legend plt.legend(handles=[ mpatches.Patch(color=colors[i], label=s) for i, s in enumerate(states) ]) # Setup the xaxis ax.xaxis_date() ax.xaxis.set_major_formatter(DateFormatter('%H:%M')) ax.xaxis.set_major_locator(SecondLocator( interval=60 * 60)) # used to be SecondLocator(0, interval=20) plt.xlabel('Time') plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.xlim(datetime(1900, 1, 1, 0), datetime(1900, 1, 1, 23, 59)) # Setup the yaxis plt.ylabel('Date') plt.yticks(y[unique_idx], captions) plt.ylim(0, 1) plt.show()
def __init__(self,title,valueName): self.fig = Figure() self.ax = self.fig.add_subplot(111) self.title = title self.valueName = valueName FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.fig.suptitle(self.title) #set title self.ax.set_xlabel("time") self.ax.set_ylabel(self.valueName) self.ax.legend() #self.ax.set_ylim(Y_MIN, Y_MAX) self.ax.xaxis.set_major_locator(MinuteLocator()) # every minute is a major locator self.ax.xaxis.set_minor_locator(SecondLocator([5, 10, 15, 20, 25])) # every 10 second is a minor locator self.ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S')) # tick label formatter self.curveObj = None # draw object
def read_data(self): dataframe = pd.read_csv(filepath_or_buffer=self.inputfile) real_time = np.array(dataframe["real_time"]) grTempOutdoor_1sec = np.array((dataframe["grTempOutdoor_1sec"])) # print real_time real_time_modified = [] for item in real_time: time_item = datetime.datetime.strptime(item, "%Y/%m/%d %H:%M:%S") real_time_modified.append(time_item) print real_time_modified # print grTempOutdoor_1sec # plt.plot(real_time,grTempOutdoor_1sec) # grTempHub_1sec.plot() minutes = MinuteLocator() seconds = SecondLocator() ax = plt.subplot(111) ax.xaxis.set_major_locator(minutes) ax.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d %H:%M:%S')) plt.xticks(rotation=90) plt.plot(real_time_modified, grTempOutdoor_1sec) plt.show()
def chartInit(self,chart,timescale=1.0): u"""根据timescale设置K线图和成交量图的label,xLocator等参数""" chart.grid(color='w') for tick in chart.yaxis.get_major_ticks(): tick.label1On = True tick.label2On = True tick.label1.set_fontsize(9) tick.label2.set_fontsize(9) if timescale <= 10: chart.xaxis.set_major_locator(SecondLocator([0,30])) chart.xaxis.set_major_formatter(DateFormatter('%H:%M:%S')) elif timescale <= 60: chart.xaxis.set_major_locator(MinuteLocator([0,5,10,15,20,25,30,35,40,45,50,55])) chart.xaxis.set_major_formatter(DateFormatter('%H:%M')) elif timescale <= 1800: chart.xaxis.set_major_locator(HourLocator([0,3,6,9,12,15,18,21])) chart.xaxis.set_major_formatter(DateFormatter('%H:%M')) else : chart.xaxis.set_major_locator(HourLocator([0,12])) chart.xaxis.set_major_formatter(DateFormatter('%H:%M'))
def init(): ax.clear() """ Initialize plot window and static plot elements """ # Configure x-axis and y-axis ax.xaxis.set_major_locator(MinuteLocator()) ax.xaxis.set_major_formatter(DateFormatter(time_format)) ax.xaxis.set_minor_locator(SecondLocator(bysecond=[15, 30, 45])) ax.yaxis.tick_right() ax.yaxis.set_major_formatter(FormatStrFormatter('%.5f')) # Set colors fig.set_facecolor(colortheme['bg2']) ax.set_facecolor(colortheme['bg1']) for child in ax.get_children(): if isinstance(child, spines.Spine): child.set_color(colortheme['fg1']) ax.xaxis.grid(color=colortheme['fg2'], linewidth=0.2) ax.yaxis.grid(color=colortheme['fg2'], linewidth=0.2) ax.tick_params(axis='both', colors=colortheme['fg1']) # Put more space below and above plot ax.set_ymargin(0.8) # Create title if title: ax.annotate(title, xy=(0.02, 0.945), xycoords='axes fraction', ha='left', color=colortheme['fg1']) """ Determine number of plot lines and set default values for line color, style and width """ # Generate one tick to find out how many lines must be plotted tick = f() num_lines = len(tick) - 1 # Set default values for lcolors, lstyles, lwidths and llabels lcols = lcolors if lcolors else [colortheme['fg1']] * num_lines lstys = lstyles if lstyles else ['-'] * num_lines lwids = lwidths if lwidths else [1.0] * num_lines # Check that user inputs have correct length assert (len(lcols) == num_lines) & \ (len(lstys) == num_lines) & \ (len(lwids) == num_lines) & \ (not llabels or len(llabels) == num_lines), \ 'lcolors, lstyles, lwidths and llabels must either be unspecified' \ 'or their length must equal the number of plot lines' """ Initialize interactive plot elements """ # Initialize x-axis ax.set_xlim(tick[0], tick[0] + timedelta(seconds=period + padding)) # Initialize date textbox below x-axis date_text = ax.annotate('', xy=(0.5, -0.11), xycoords='axes fraction', ha='center', color=colortheme['fg1']) timeplot.texts.append(date_text) # Initialize current tick value on y-axis value_text = ax.annotate('', xy=(1, 1), xycoords=ax.get_yaxis_transform(), xytext=(7, 0), textcoords='offset points', ha='left', va='center', color=colortheme['fg1'], bbox=dict(edgecolor=colortheme['fg1'], facecolor=colortheme['bg1'])) timeplot.texts.append(value_text) # Initialize plot lines for i in range(num_lines): line = ax.plot([], [], c=lcols[i], ls=lstys[i], lw=lwids[i])[0] if llabels: line.set_label(llabels[i]) timeplot.lines.append(line) """ Create legend """ if llabels: handles = [ line for line, label in zip(timeplot.lines, llabels) if label ] plt.legend(handles=handles, loc='lower left') return animate(tick)
#Plot function def timelines(y, xstart, xstop, color='b'): """Plot timelines at y from xstart to xstop with given color.""" plt.hlines(y, xstart, xstop, color, lw=4) plt.scatter(xstart, y, s=100, c=color, marker=".", lw=2, edgecolor=color) # plt.vlines(xstart, y+0.03, y-0.03, color, lw=2) plt.scatter(xstop, y, s=100, c=color, marker=".", lw=2, edgecolor=color) # plt.vlines(xstop, y+0.03, y-0.03, color, lw=2) #Plot ok tl black timelines(y[is_ok], start[is_ok], stop[is_ok], 'k') #Plot fail tl red timelines(y[not_ok], start[not_ok], stop[not_ok], 'r') #Setup the plot ax = plt.gca() ax.xaxis_date() myFmt = DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(myFmt) ax.xaxis.set_major_locator( SecondLocator(interval=20)) # used to be SecondLocator(0, interval=20) #To adjust the xlimits a timedelta is needed. delta = (stop.max() - start.min()) / 10 plt.yticks(y[unique_idx], captions) plt.ylim(0, 1) plt.xlim(start.min() - delta, stop.max() + delta) plt.xlabel('Time') plt.show()
def plot_cpid(ax, times, cpid, mode, cpidchange_lims): """Plots control program ID (cpid) panel at position pos. Parameters ---------- ax : a MPL axis object to plot to times : list a list of the times of the beam soundings cpid : list a list of the cpids of the beam soundings. mode : list a list of the ifmode param cpidchange_lims : int Limit on the number of times the cpid can change Returns ------- Nothing. Example ------- plot_cpid(ax,times,cpid,mode, cpidchange_lims=10) Written by AJ 20121002 Modified by ASR 20150916 """ from davitpy import pydarn from matplotlib.ticker import MultipleLocator from matplotlib.dates import SecondLocator from matplotlib.dates import date2num from datetime import timedelta import numpy as np oldCpid = -9999999 # Format the yaxis. ax.yaxis.tick_left() ax.yaxis.set_tick_params(direction='out') ax.set_ylim(bottom=0, top=1) ax.yaxis.set_minor_locator(MultipleLocator(1)) ax.yaxis.set_tick_params(direction='out', which='minor') # Draw the axes. ax.plot_date(date2num(times), np.arange(len(times)), fmt='w', tz=None, xdate=True, ydate=False, alpha=0.0) # Initialize CPID change counter cpid_change = 0 # Label the CPIDs. for i in range(0, len(times)): if (cpid[i] != oldCpid): cpid_change += 1 # If the cpid is changing too much, it won't be readible if (cpid_change >= cpidchange_lims): # Clear the current axis ax.cla() # Kick out error messages diff_time = (times[-1] - times[0]).total_seconds() / 2. cpid_time = times[0] + timedelta(seconds=diff_time) temp = ', '.join([str(x) for x in list(set(cpid))]) cpid_text = 'CPIDs: ' + temp ax.text(cpid_time, .5, cpid_text, ha='center', va='center', size=10) logging.error('CPID is changing too frequently to be ' 'legibly printed. Please consider using ' 'radDataOpen cp param. CPIDs found: ' + str(list(set(cpid)))) break ax.plot_date( [date2num(times[i]), date2num(times[i])], [0, 1], fmt='k-', tz=None, xdate=True, ydate=False) oldCpid = cpid[i] s = ' ' + pydarn.radar.radUtils.getCpName(oldCpid) istr = ' ' if (mode[i] == 1): istr = ' IF' if (mode == 0): istr = ' RF' ax.text(times[i], .5, ' ' + str(oldCpid) + s + istr, ha='left', va='center', size=10) # Format the xaxis. xmin = date2num(times[0]) xmax = date2num(times[len(times) - 1]) xrng = (xmax - xmin) inter = int(round(xrng / 6. * 86400.)) inter2 = int(round(xrng / 24. * 86400.)) ax.xaxis.set_minor_locator(SecondLocator(interval=inter2)) ax.xaxis.set_major_locator(SecondLocator(interval=inter)) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(0) # Identify the CPID axis with a label. fig = ax.get_figure() bb = ax.get_position() x0 = bb.x0 y0 = bb.y0 height = bb.height width = bb.width pos = [x0, y0, width, height] fig.text(pos[0] - .07, pos[1] + pos[3] / 2., 'CPID', ha='center', va='center', size=8.5, rotation='vertical') ax.set_yticks([])
matplotlib.rc('font', **font_base) matplotlib.rc('xtick', labelsize=12) # matplotlib.rc('xtick', labelsize=30) matplotlib.rc('ytick', labelsize=16) # matplotlib.rc('ytick', labelsize=30) # matplotlib.rc('legend', fontsize=12) # matplotlib.rc('legend', labelspacing=0.2) # Artist shape used by annotations el = Ellipse((2, -1), 0.5, 0.5) # Formatter to change x values ticks minutes = MinuteLocator(interval=4) minutes_formatter = DateFormatter("%M:%S") secondes = SecondLocator(interval=10) secondes_formatter = DateFormatter("%M:%S") ####################################### # Classes, Methods, Functions : # ####################################### def convert_to_datetime(step, start=datetime.datetime(2014, 1, 1)): """ This parser convert to a real datetime format """ for el in step: yield start + datetime.timedelta(seconds=int(el))
def graph(destination): with get_conn() as conn: cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) destination_history_query = """ WITH intervals AS ( SELECT begin_time, LEAD(begin_time) OVER ( ORDER BY begin_time ) AS end_time FROM generate_series( now() - INTERVAL '1 hours', now(), INTERVAL '1 minutes' ) begin_time ) SELECT i.begin_time AT TIME ZONE 'Europe/Berlin' AS begin_time, i.end_time AT TIME ZONE 'Europe/Berlin' AS end_time, p.destination, count(p.pingtime), round(avg(p.pingtime),2) AS avg, max(p.pingtime), min(p.pingtime) FROM intervals i LEFT JOIN pings p ON p.recorded_at >= i.begin_time AND p.recorded_at < i.end_time WHERE i.end_time IS NOT NULL AND destination = %s GROUP BY i.begin_time, i.end_time, p.destination ORDER BY i.begin_time ASC; """ cur.execute(destination_history_query, (destination, )) times = cur.fetchall() fig = Figure(figsize=(30, 8), dpi=80, facecolor='w', edgecolor='k', tight_layout=True) ax = fig.add_subplot(111) begin_times = [row['begin_time'] for row in times] maxs = [row['max'] for row in times] ax.plot_date(x=begin_times, y=maxs, label='max', linestyle='solid') avgs = [row['avg'] for row in times] ax.plot_date(x=begin_times, y=avgs, label='avg', linestyle='solid') mins = [row['min'] for row in times] ax.plot_date(x=begin_times, y=mins, label='min', linestyle='solid') ax.set_xlabel('Time') ax.set_ylabel('Round Trip (ms)') ax.set_ylim(bottom=0) ax.xaxis_date() my_fmt = DateFormatter('%H:%M') ax.xaxis.set_major_formatter(my_fmt) ax.xaxis.set_major_locator(SecondLocator(interval=60)) ax.legend() ax.grid() png_output = io.BytesIO() fig.set_canvas(FigureCanvasAgg(fig)) fig.savefig(png_output, transparent=True, format='png') response = make_response(png_output.getvalue()) response.headers['content-type'] = 'image/png' return response
def plot(self, datax, datay): print("Start Plot()") self.ax.set_xlabel("time of data generator") self.ax.set_ylabel('random data value') self.ax.legend() self.ax.set_ylim(Y_MIN, Y_MAX) self.ax.xaxis.set_major_locator( MinuteLocator()) # every minute is a major locator self.ax.xaxis.set_minor_locator(SecondLocator( [10, 20, 30, 40, 50])) # every 10 second is a minor locator self.ax.xaxis.set_major_formatter( DateFormatter('%H:%M:%S')) # tick label formatter self.curveObj = None # draw object plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 # 有中文出现的情况,需要u'内容' plt.xlabel(u'概率(%)') plt.ylabel(u'数值') plt.title(u'P-III曲线测试点图') xaxLabel = [ 0.01, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 98, 99, 99.5, 99.9, 99.99 ] xaxValuepre = [i / 100 for i in xaxLabel] X = scst.norm() xaxValue = (X.ppf(xaxValuepre) - X.ppf(0.0001)) / ( (X.ppf(0.9999) - X.ppf(0.0001))) * 100 ax = plt.subplot(111) # 注意:一般都在ax中设置,不再plot中设置 ValRateX = (X.ppf(ValRate) - X.ppf(0.0001)) / ( (X.ppf(0.9999) - X.ppf(0.0001))) * 100 plt.scatter(ValRateX, ValList, marker='o') # 横坐标根据海森机率格纸要求进行变换 ax.set_xticks(xaxValue) ax.set_xticklabels(xaxLabel) from matplotlib.ticker import MultipleLocator, FormatStrFormatter ymajorLocator = MultipleLocator(200) # 将y轴主刻度标签设置为0.5的倍数 ymajorFormatter = FormatStrFormatter('%1.1f') # 设置y轴标签文本的格式 yminorLocator = MultipleLocator(40) # 将此y轴次刻度标签设置为0.1的倍数 ax.yaxis.set_major_locator(ymajorLocator) ax.yaxis.set_major_formatter(ymajorFormatter) ax.yaxis.set_minor_locator(yminorLocator) ax.xaxis.grid(True, which='major') # x坐标轴的网格使用主刻度 ax.yaxis.grid(True, which='major') alpha = 4 / (Cs * Cs) beta = 2 / (ValEve * Cv * Cs) a0 = ValEve * (1 - 2 * Cv / Cs) Y = scst.gamma(alpha) def Fip(x): return Cs / 2 * Y.ppf(1 - x) - (2 / Cs) P3List = np.arange(0, 1, 0.0001).tolist() # P3List=[0.00000001]+P3List+[0.99999999999] P3XPre = [i for i in P3List] P3Y = [(1 + Cv * Fip(i)) * ValEve for i in P3XPre] P3X = (X.ppf(P3XPre) - X.ppf(0.0001)) / ( (X.ppf(0.9999) - X.ppf(0.0001))) * 100 plt.plot(P3X, P3Y, 'r') # G=scst.gumbel_r() #参数不清楚 plt.show() self.draw()
def draw_axes(myFig, times, rad, cpid, bmnum, nrang, frang, rsep, bottom, yrng=-1, coords='gate', pos=[.1, .05, .76, .72], xtick_size=9, ytick_size=9, xticks=None, axvlines=None): """ Draws empty axes for an rti plot. Parameters ---------- myFig : the MPL figure we are plotting to times : list a list of datetime objects referencing the beam soundings rad : str 3 letter radar code cpid : list list of the cpids or the beam soundings bmnum : int beam number being plotted nrang : list list of nrang for the beam soundings frang : list list of frang of the beam soundings rsep : list list of rsep of the beam soundings bottom : bool flag indicating if we are at the bottom of the figure yrng : Optional[list] range of y axis, -1=autoscale (default) coords : Optional[ ] y axis coordinate system, acceptable values are 'geo', 'mag', 'gate', 'rng' pos : Optional[ ] position of the plot xtick_size : Optional[ ] fontsize of xtick labels ytick_size : Optional[ ] fontsize of ytick labels xticks : Optional[list] datetime.datetime objects indicating the location of xticks axvlines : Optional[list] datetime.datetime objects indicating the location vertical lines marking the plot Returns ------- ax : an axes object Example ------- ax = draw_axes(myFig,times,rad,cpid,beam,nrang,frang,rsep,0) Written by AJ 20121002 Modified by ASR 20150917 (refactored) """ from davitpy import pydarn from matplotlib.ticker import MultipleLocator, FormatStrFormatter from matplotlib.dates import SecondLocator, DateFormatter, date2num from matplotlib.lines import Line2D import numpy as np nrecs = len(times) # Add an axes object to the figure. ax = myFig.add_axes(pos) ax.yaxis.set_tick_params(direction='out') ax.xaxis.set_tick_params(direction='out') ax.yaxis.set_tick_params(direction='out', which='minor') ax.xaxis.set_tick_params(direction='out', which='minor') # Draw the axes. ax.plot_date(date2num(times), np.arange(len(times)), fmt='w', tz=None, xdate=True, ydate=False, alpha=0.0) # Determine the yaxis min/max unless it's been specified if (yrng == -1): ymin, ymax = 99999999, -999999999 if (coords != 'gate'): oldCpid = -99999999 for i in range(len(cpid)): if (cpid[i] == oldCpid): continue oldCpid = cpid[i] if (coords == 'geo' or coords == 'mag'): # HACK NOT SURE IF YOU CAN DO THIS(Formatting)! site = pydarn.radar.network().getRadarByCode(rad) \ .getSiteByDate(times[i]) myFov = pydarn.radar.radFov.fov(site=site, ngates=nrang[i], nbeams=site.maxbeam, rsep=rsep[i], coords=coords, date_time=times[i]) if (myFov.latFull[bmnum].max() > ymax): ymax = myFov.latFull[bmnum].max() if (myFov.latFull[bmnum].min() < ymin): ymin = myFov.latFull[bmnum].min() else: ymin = 0 if (nrang[i] * rsep[i] + frang[i] > ymax): ymax = nrang[i] * rsep[i] + frang[i] else: ymin, ymax = 0, max(nrang) else: ymin, ymax = yrng[0], yrng[1] # Format the xaxis. xmin = date2num(times[0]) xmax = date2num(times[len(times) - 1]) xrng = (xmax - xmin) inter = int(round(xrng / 6. * 86400.)) inter2 = int(round(xrng / 24. * 86400.)) ax.xaxis.set_minor_locator(SecondLocator(interval=inter2)) ax.xaxis.set_major_locator(SecondLocator(interval=inter)) # If axis is at bottom of figure, draw xticks. if (not bottom): for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(0) else: if xticks is not None: ax.xaxis.set_ticks(xticks) if axvlines is not None: for line in axvlines: ax.axvline(line, color='0.25', ls='--') for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(xtick_size) ax.xaxis.set_major_formatter(DateFormatter('%H:%M')) ax.xaxis.set_label_text('UT') # Set ytick size. for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(ytick_size) # Format yaxis depending on coords. if (coords == 'gate'): ax.yaxis.set_label_text('Range gate', size=10) ax.yaxis.set_major_formatter(FormatStrFormatter('%d')) ax.yaxis.set_major_locator(MultipleLocator((ymax - ymin) / 5.)) ax.yaxis.set_minor_locator(MultipleLocator((ymax - ymin) / 25.)) elif (coords == 'geo' or coords == 'mag'): if (coords == 'mag'): ax.yaxis.set_label_text('Mag Lat [deg]', size=10) else: ax.yaxis.set_label_text('Geo Lat [deg]', size=10) elif (coords == 'rng'): ax.yaxis.set_label_text('Slant Range [km]', size=10) ax.yaxis.set_major_formatter(FormatStrFormatter('%d')) ax.yaxis.set_major_locator(MultipleLocator(1000)) ax.yaxis.set_minor_locator(MultipleLocator(250)) ax.set_ylim(bottom=ymin, top=ymax) return ax