我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用matplotlib.pyplot.vlines()。
def lineplot(x=None, y=None, data=None, order=None, palette=None, linewidth=0, ax=None, orient="v", **kwargs): if ax is None: ax = plt.gca() if not order: order = y.unique() order = list(sorted(order)) func = plt.vlines if orient=="v" else plt.hlines for i, lev in enumerate(order): func(x[y == lev], i + 0.025, i + 0.975, colors=palette[i], linewidth=1) if len(order) < 2: ax.set(yticks=[]) else: ax.set(yticks=[0.5 + n for n in range(len(order))]) ax.set(yticklabels=order) ax.set(xlim=(0, max(x))) ax.set(ylim=(len(order), 0)) return ax
def plot_stream_and_arrival(st, picks, origin_time, predict_arrivals): print("--------> Plot...") print(origin_time) plt.figure(figsize=(10, 15)) ntraces = len(st) for idx, tr in enumerate(st): ax = plt.subplot(ntraces, 1, idx+1) ax.axis('off') # ax.get_xaxis().set_visible(False) plt.plot(tr.data) arrival_index, pick_type = extract_arrival_index(picks[tr.id]) ymin, ymax = ax.get_ylim() event_index = (origin_time - tr.stats.starttime) / tr.stats.delta plt.vlines([event_index], ymin, ymax, linestyles="dotted", color='g', linewidth=2) pred_arrival_index = \ event_index + predict_arrivals[idx] / tr.stats.delta plt.vlines([pred_arrival_index], ymin, ymax, linestyles="dashdot", color='k', linewidth=3) if pick_type is not None: plt.vlines([arrival_index], ymin, ymax, color='r', linewidth=2) plt.tight_layout() plt.show()
def plot_arrival_window(trace, windows, origin_time): plt.plot(trace.data) ax = plt.gca() ymin, ymax = ax.get_ylim() idx = (UTCDateTime(windows["pick_arrival"]) - trace.stats.starttime) / \ trace.stats.delta plt.vlines([idx], ymin, ymax, linestyles="dotted", color='r') idx = (UTCDateTime(windows["theo_arrival"]) - trace.stats.starttime) / \ trace.stats.delta plt.vlines([idx], ymin, ymax, linestyles="dotted", color='b') idx = (origin_time - trace.stats.starttime) / \ trace.stats.delta plt.vlines([idx], ymin, ymax, linestyles="dotted", color='b') plt.show()
def deisochart(envelopes, unassigned): import matplotlib.pyplot as pyt from random import seed, shuffle seed(1) def lines(thing, charge = None, **etc): pyt.vlines(zip(*thing)[0], [0]*len(thing), zip(*thing)[1], **etc) if charge: for pt in thing: pyt.text(pt[0], pt[1], str(charge)) lines(unassigned, color = 'b') length = len(sum(envelopes.values(), [])) colors = pyt.cm.Set1([x/float(length) for x in range(0, length)]) shuffle(colors) i = 0 for chg, chgEnvs in envelopes.items(): for env in chgEnvs: label = "%s(%s)" % (i, chg) lines(env, charge = label, color = colors[i], linewidth = 3) i += 1 pyt.show()
def plot_samples(S, axis_list=None): plt.scatter(S[:, 0], S[:, 1], s=2, marker='o', zorder=10, color='steelblue', alpha=0.5) if axis_list is not None: colors = ['orange', 'red'] for color, axis in zip(colors, axis_list): axis /= axis.std() x_axis, y_axis = axis # Trick to get legend to work plt.plot(0.1 * x_axis, 0.1 * y_axis, linewidth=2, color=color) plt.quiver(0, 0, x_axis, y_axis, zorder=11, width=0.01, scale=6, color=color) plt.hlines(0, -3, 3) plt.vlines(0, -3, 3) plt.xlim(-3, 3) plt.ylim(-3, 3) plt.xlabel('x') plt.ylabel('y')
def plot(nb, pvec, avec, title): """Plotting function.""" pvecm = pvec.mean(1) avecm = avec.mean(1) plt.subplot(1, 4, nb) plt.vlines(pvecm, -10, 500, color='#ab4642') plt.hlines(avecm, -10, 500, color='slateblue') plt.xlabel('Frequency for phase (hz') plt.ylabel('Frequency for amplitude.mean(1)') plt.title(title) plt.xlim([0, 30]) plt.ylim([60, 200])
def deisocompare(envelopes1, unassigned1, envelopes2, unassigned2): import matplotlib.pyplot as pyt from random import seed, shuffle seed(1) def lines(thing, charge = None, upness = 1, **etc): pyt.vlines(zip(*thing)[0], [0]*len(thing), [x*upness for x in zip(*thing)[1]], **etc) if charge: for pt in thing: pyt.text(pt[0], upness * pt[1], str(charge)) lines(unassigned1, color = 'b') length = len(sum(envelopes1.values(), [])) colors = pyt.cm.Set1([x/float(length) for x in range(0, length)]) shuffle(colors) i = 0 for chg, chgEnvs in envelopes1.items(): for env in chgEnvs: label = "%s(%s)" % (i, chg) lines(env, charge = label, color = colors[i], linewidth = 3) i += 1 lines(unassigned2, upness = -1, color = 'b') length = len(sum(envelopes2.values(), [])) colors = pyt.cm.Set1([x/float(length) for x in range(0, length)]) shuffle(colors) i = 0 for chg, chgEnvs in envelopes2.items(): for env in chgEnvs: label = "%s(%s)" % (i, chg) lines(env, charge = label, upness = -1, color = colors[i], linewidth = 3) i += 1 pyt.show()
def Vlines(xs, y1, y2, **options): """Plots a set of vertical lines. Args: xs: sequence of x values y1: sequence of y values y2: sequence of y values options: keyword args passed to plt.vlines """ options = _UnderrideColor(options) options = _Underride(options, linewidth=1, alpha=0.5) plt.vlines(xs, y1, y2, **options)
def Hlines(ys, x1, x2, **options): """Plots a set of horizontal lines. Args: ys: sequence of y values x1: sequence of x values x2: sequence of x values options: keyword args passed to plt.vlines """ options = _UnderrideColor(options) options = _Underride(options, linewidth=1, alpha=0.5) plt.hlines(ys, x1, x2, **options)
def _print_junction(self): bw = self.game_params['board_width'] lw = self.game_params['lane_width'] # road marks plt.vlines(lw, -bw, -lw) plt.vlines(-lw, -bw, -lw) plt.vlines(-lw, lw, bw) plt.vlines(lw, lw, bw) plt.hlines(-lw, -bw, -lw) plt.hlines(-lw, lw, bw) plt.hlines(lw, -bw, -lw) plt.hlines(lw, lw, bw) # lane marks plt.vlines(0, -bw, -lw, linestyles='dashed') plt.vlines(0, lw, bw, linestyles='dashed') plt.hlines(0, -bw, -lw, linestyles='dashed') plt.hlines(0, lw, bw, linestyles='dashed') # stopping lines plt.hlines(-lw, 0, lw, linestyles='solid') plt.hlines(-lw-0.01, 0, lw, linestyles='solid') plt.hlines(lw, -lw, 0, linestyles='solid') plt.hlines(lw+0.01, -lw, 0, linestyles='solid') plt.vlines(-lw, -lw, 0, linestyles='solid') plt.vlines(-lw-0.01, -lw, 0, linestyles='solid') plt.vlines(lw, 0, lw, linestyles='solid') plt.vlines(lw+0.01, 0, lw, linestyles='solid') # print rails # self.ax.add_patch(Circle(xy=(lw,-lw), radius=lw/2, edgecolor='k', facecolor='none')) # self.ax.add_patch(Circle(xy=(-lw,-lw), radius=3*lw/2, edgecolor='k', facecolor='none'))
def plot_spectrogram(self,store_key,condition,fig_mark=[0],y_lim=[0,100]): ''' Args store_key (string): define which data to be analyzed in the workspace condition (string): define which conditions will be plotted fig_mark (list): Draw vertical lines at the time points in the list. Default: [0] y_lim (list): set limits of y-axis Default: [0,100] Returns {'frequency':frequency, 'time':analog signal time, 'data':spectrogram value} ''' time = self.store[self.store.keys()[0]][store_key]['time'].value freq = self.store[self.store.keys()[0]][store_key]['frequency'].value datas_all = list() for ite_file in self.store.keys(): datas_all.append(self.store[ite_file][store_key]['data'][str(condition)].value) datas_all = np.array(datas_all) specgram = datas_all.mean(axis=0) vmin = specgram[(y_lim[0]<freq) & (freq<y_lim[1])].min() vmax = specgram[(y_lim[0]<freq) & (freq<y_lim[1])].max() halfbin_time = (time[1] - time[0]) / 2.0 halfbin_freq = (freq[1] - freq[0]) / 2.0 specgram_1 = np.flipud(specgram) # center bin extent = (time[0] - halfbin_time, time[-1] + halfbin_time, freq[0] - halfbin_freq, freq[-1] + halfbin_freq) plt.figure() plt.imshow(specgram_1, interpolation="nearest", extent=extent,cmap=plt.cm.jet, vmin=vmin, vmax=vmax) plt.axis('tight') fig_mark = [ite/1000.0 for ite in fig_mark] if y_lim is not False: plt.ylim(y_lim) plt.vlines(fig_mark,y_lim[0],y_lim[1],color='r') plt.colorbar() plt.title(str(condition)) return {'frequency':freq,'time':time,'data':specgram} # plot scalar data (e.g. reaction time) in population level
def plot_spectrogram(self,store_key,condition,fig_mark=[0],y_lim=[0,100]): ''' Args store_key (string): define which data to be analyzed in the workspace condition (string): define which conditions will be plotted fig_mark (list): Draw vertical lines at the time points in the list. Default: [0] y_lim (list): set limits of y-axis Default: [0,100] Returns {'frequency':frequency, 'time':analog signal time, 'data':spectrogram value} ''' time = self.store[list(self.store.keys())[0]][store_key]['time'].value freq = self.store[list(self.store.keys())[0]][store_key]['frequency'].value datas_all = list() for ite_file in list(self.store.keys()): datas_all.append(self.store[ite_file][store_key]['data'][str(condition)].value) datas_all = np.array(datas_all) specgram = datas_all.mean(axis=0) vmin = specgram[(y_lim[0]<freq) & (freq<y_lim[1])].min() vmax = specgram[(y_lim[0]<freq) & (freq<y_lim[1])].max() halfbin_time = (time[1] - time[0]) / 2.0 halfbin_freq = (freq[1] - freq[0]) / 2.0 specgram_1 = np.flipud(specgram) # center bin extent = (time[0] - halfbin_time, time[-1] + halfbin_time, freq[0] - halfbin_freq, freq[-1] + halfbin_freq) plt.figure() plt.imshow(specgram_1, interpolation="nearest", extent=extent,cmap=plt.cm.jet, vmin=vmin, vmax=vmax) plt.axis('tight') fig_mark = [ite/1000.0 for ite in fig_mark] if y_lim is not False: plt.ylim(y_lim) plt.vlines(fig_mark,y_lim[0],y_lim[1],color='r') plt.colorbar() plt.title(str(condition)) return {'frequency':freq,'time':time,'data':specgram} # plot scalar data (e.g. reaction time) in population level
def aligned_raster(spikes, stim_ds, stim_name, padding, title, stim_data): """Returns a pyplot figure object with aligned rasters based on stim_ds and stim_name. spike_list -- sequence of spike times, in seconds stim_ds -- Bark event dataset, with time in seconds stim_name -- string padding -- 2-tuple, in seconds, of before and after padding title -- string stim_data -- Stimulus object, or None """ f = plt.figure() offset = 0 stim_events = stim_ds[stim_ds['name'] == stim_name] if stim_events.empty: msg = 'stimulus "{}" not found in {}' raise KeyError(msg.format(stim_name, stim_ds.name)) if stim_data is not None: extended_stimulus = pad_stimulus(stim_data, padding) arrstim = np.array(extended_stimulus.data) plt.plot((arrstim / max(abs(arrstim))) + STIM_OFFSET * OFFSET_STEP) for stim_event in stim_events.itertuples(): start = stim_event.start - padding[0] stop = stim_event.stop + padding[1] offset -= OFFSET_STEP curr_spks = [s - start for s in spikes if s >= start and s <= stop] if stim_data is not None: curr_spks = [sec2samp(s, stim_data.sampling_rate) for s in curr_spks] if curr_spks: col = 'black' else: # if there are no spikes, it messes with plot alignment curr_spks = [0] col = 'white' height = offset + RASTER_LH_PROP * OFFSET_STEP plt.vlines(curr_spks, offset, height, linewidths=RASTER_LW, color=col) plt.title(title, fontsize=TITLE_SIZE) xmax = stop - start xstep = xmax / NUM_XTICKS xt = np.arange(padding[0], xmax, xstep) if stim_data is not None: xmax = sec2samp(xmax, stim_data.sampling_rate) xt = [sec2samp(t, stim_data.sampling_rate) for t in xt] plt.xlim([(-0.05 * xmax), (1.05 * xmax)]) plt.xticks(xt, ['{:.2f}'.format(xstep * t) for t in range(0, NUM_XTICKS)]) plt.yticks([]) plt.xlabel('Time (s)', fontsize=AXIS_LABEL_SIZE) plt.ylabel('Event repetitions', fontsize=AXIS_LABEL_SIZE) return f
def line(data, file_path, style=[], title='', xlabel='', ylabel='', logx=False, logy=False, vlines=[]): """Plots a line plot using matplotlib. Parameters ---------- data : pd.DataFrame two column df with x and y values file_path : str path to save figure title : str graph title xlabel : str x-axis label ylabel : str y-axis label vlines : list of int draw vertical lines at positions """ # plot data data.plot(kind='line', style=style) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # log scale if neccessary if logx: plt.xscale('log') if logy: plt.yscale('log') # plot vertical lines ymin, ymax = plt.ylim() # get plotting range of y-axis for l in vlines: plt.vlines(l, ymin=ymin, ymax=ymax, color='red') plt.tight_layout() # adjust plot margins plt.savefig(file_path) # save figure plt.clf() # clear figure plt.close()
def plottemperature(skirtrun): simulation = skirtrun.simulation() # setup the figure figure = plt.figure(figsize=(10,6)) # load the mass and temperature data for all cells filepath = simulation.outfilepath("ds_celltemps.dat") M,T = np.loadtxt(arch.opentext(filepath), unpack=True) Mtot = M.sum() if Mtot > 0: # calculate the average temperature and corresponding standard deviation Tavg = np.average(T, weights=M) Tstd = np.sqrt( (M*((T-Tavg)**2)).sum()/Mtot ) skew = (M*((T-Tavg)**3)).sum()/Mtot/ Tstd**3 kurtosis = (M*((T-Tavg)**4)).sum()/Mtot/ Tstd**4 - 3 # plot the histogram Tmax = 40 T[T>Tmax] = Tmax plt.hist(T.flatten(), weights=M, bins=Tmax, range=(0,Tmax), histtype='step', normed=True, log=True, color='r') # add vertical lines at the average temperature plus-min one sigma plt.vlines(Tavg, 1e-4, 1, colors='m', linestyle='solid') plt.vlines((Tavg+Tstd,Tavg-Tstd), 1e-4, 1, colors='m', linestyle='dashed') plt.vlines((Tavg+Tstd*skew,), 1e-4, 1, colors='b', linestyle='dotted') # add textual information about the statistics plt.text(Tmax-1, 0.2, " mean = {:.2f} K\n stddev = {:.2f} K\n skew = {:.3f}\n kurtosis = {:.3f}" \ .format(Tavg, Tstd, skew, kurtosis), horizontalalignment='right', backgroundcolor='w') # add axis labels and title plt.grid('on') plt.xlabel("T (K)", fontsize='medium') plt.ylabel("Dust Mass (normalized)", fontsize='medium') plt.ylim(1e-4, 1) plt.title("runid {} -- {}".format(skirtrun.runid(), skirtrun.prefix()), fontsize='medium') # save the figure plotpath = os.path.join(skirtrun.vispath(), skirtrun.prefix()+"_dust_temperature.pdf") plt.savefig(plotpath, bbox_inches='tight', pad_inches=0.25) plt.close() print "Created PDF plot file " + plotpath # ----------------------------------------------------------------------
def plotMAP(x, ax=None, error=0.01, frac=[0.65,0.95, 0.975], usehpd=True, hist={'histtype':'step'}, vlines={}, fill={}, optbins={'method':'freedman'}, *args, **kwargs): """ Plot the MAP of a given sample and add statistical info If not specified, binning is assumed from the error value or using mystats.optbins if available. if mystats module is not available, hpd keyword has no effect inputs: x dataset keywords ax axe object to use during plotting error error to consider on the estimations frac fractions of sample to highlight (def 65%, 95%, 97.5%) hpd if set, uses mystats.hpd to estimate the confidence intervals hist keywords forwarded to hist command optbins keywords forwarded to mystats.optbins command vlines keywords forwarded to vlines command fill keywords forwarded to fill command """ _x = np.ravel(x) if ax is None: ax = plt.gca() if not ('bins' in hist): bins = get_optbins(x, method=optbins['method'], ret='N') n, b, p = ax.hist(_x, bins=bins, *args, **hist) else: n, b, p = ax.hist(_x, *args, **hist) c = 0.5 * (b[:-1] + b[1:]) # dc = 0.5 * (b[:-1] - b[1:]) ind = n.argmax() _ylim = ax.get_ylim() if usehpd is True: _hpd = hpd(_x, 1 - 0.01) ax.vlines(_hpd, _ylim[0], _ylim[1], **vlines) for k in frac: nx = hpd(_x, 1. - k) ax.fill_between(nx, _ylim[0], _ylim[1], alpha=0.4 / float(len(frac)), zorder=-1, **fill) else: ax.vlines(c[ind], _ylim[0], _ylim[1], **vlines) cx = c[ n.argsort() ][::-1] cn = n[ n.argsort() ][::-1].cumsum() for k in frac: sx = cx[np.where(cn <= cn[-1] * float(k))] sx = [sx.min(), sx.max()] ax.fill_between(sx, _ylim[0], _ylim[1], alpha=0.4 / float(len(frac)), zorder=-1, **fill) theme(ax=ax) ax.set_xlabel(r'Values') ax.set_ylabel(r'Counts')
def plot_bstr(bands_node, kpoints_node=None, title=None, efermi=None, use_parent_calc=False, **kwargs): ''' py:function:: plot_bstr(bands_node[, kpoints_node=None]) Use matplotlib to plot the bands stored in a BandsData node. A KpointsData node can optionally be given as a fallback for kpoint labels. The caller is responsible for giving a node with matching labels (as in they are in/out nodes of the same calculation). :param BandsData bands_node: The BandsData node will be searched labels first :param KpointsData kpoints_node: The optional KpointsData node will be searched only if no labels are present on the BandsData node. No consistency checks are performed. :return: the matplotlib figure containing the plot ''' fig = plt.figure() title = title or 'Band Structure (pk=%s)' % bands_node.pk bands = bands_node.get_bands() _, nkp, _ = get_bs_dims(bands) plot_bands(bands_node, **kwargs) parent_calc = None if use_parent_calc: inputs = bands_node.get_inputs() parent_calc = inputs[0] if inputs else None efermi = get_efermi(parent_calc) kpoints_node = get_kp_node(parent_calc) if efermi: plt.hlines(efermi, plt.xlim()[0], nkp - 1, linestyles='dashed') plt.yticks( list(plt.yticks()[0]) + [efermi], [str(l) for l in plt.yticks()[0]] + [r'$E_{fermi}$']) try: kpx, kpl = get_kp_labels(bands_node, kpoints_node) plt.xticks(kpx, kpl) plt.vlines(kpx, plt.ylim()[0], plt.ylim()[1]) except Exception: # pylint: disable=broad-except pass plt.ylabel('Dispersion') plt.suptitle(title) return fig