def plot_section_scalarfield(self, section_name, sn, levels=50, show_faults=True, show_topo=True, lithback=True): assert self.model.solutions.sections is not None, 'no sections for plotting defined' if self.model.grid.topography is None: show_topo = False shapes = self.model.grid.sections.resolution fig = plt.figure(figsize=(16, 10)) axes = fig.add_subplot(1, 1, 1) j = np.where(self.model.grid.sections.names == section_name)[0][0] l0, l1 = self.model.grid.sections.get_section_args(section_name) if show_faults: self.extract_section_fault_lines(section_name, zorder=9) if show_topo: xy = self.make_topography_overlay_4_sections(j) axes.fill(xy[:, 0], xy[:, 1], 'k', zorder=10) axes.contour(self.model.solutions.sections_scalfield[sn][l0:l1].reshape(shapes[j][0], shapes[j][1]).T, # origin='lower', levels=levels, cmap='autumn', extent=[0, self.model.grid.sections.dist[j], self.model.grid.regular_grid.extent[4], self.model.grid.regular_grid.extent[5]], zorder=8) axes.set_aspect('equal') if lithback: axes.imshow(self.model.solutions.sections[0][l0:l1].reshape(shapes[j][0], shapes[j][1]).T, origin='lower', cmap=self._cmap, norm=self._norm, extent=[0, self.model.grid.sections.dist[j], self.model.grid.regular_grid.extent[4], self.model.grid.regular_grid.extent[5]]) labels, axname = self._make_section_xylabels(section_name, len(axes.get_xticklabels())) pos_list = np.linspace(0, self.model.grid.sections.dist[j], len(labels)) axes.xaxis.set_major_locator(FixedLocator(nbins=len(labels), locs=pos_list)) axes.xaxis.set_major_formatter(FixedFormatter((labels))) axes.set(title=self.model.grid.sections.names[j], xlabel=axname, ylabel='Z')
def set_longitude_grid(self, degrees): # Copied from matplotlib.geo.GeoAxes.set_longitude_grid and modified number = int(360.0 // degrees) + 1 self.xaxis.set_major_locator( FixedLocator(np.linspace(0, 2 * np.pi, number, True)[1:-1])) self._longitude_degrees = degrees self.xaxis.set_major_formatter(self.RaFormatter(degrees))
def colorbar(change_ticks=True, obj=None, num_int=6, ax=None, cax=None, orientation='vertical', shrink=0.5, fixed_ticks=None, **kw): if obj is None: cbar = pl.colorbar(shrink=shrink, aspect=15, ax=ax, cax=cax, orientation=orientation, **kw) else: cbar = pl.colorbar(obj, shrink=shrink, aspect=15, ax=ax, cax=cax, orientation=orientation, **kw) if change_ticks is True: if fixed_ticks is not None: cbar.locator = FixedLocator(fixed_ticks) else: cbar.locator = MaxNLocator(num_int) cbar.update_ticks() return cbar
def set_longitude_grid(self, degrees): # Copied from matplotlib.geo.GeoAxes.set_longitude_grid and modified super(AstroDegreesMollweideAxes, self).set_longitude_grid(degrees) number = (360.0 / degrees) + 1 self.xaxis.set_major_locator( FixedLocator( np.linspace(0, 2*np.pi, number, True)[1:-1]))
def plot_objective_function(read_dir): M = pd.read_csv(read_dir / "M.csv", header=None).to_numpy() D = pd.read_csv(read_dir / "D.csv", header=None).to_numpy() F = pd.read_csv(read_dir / "f.csv", header=None).to_numpy() resX = pd.read_csv(read_dir / "resX.csv", header=None).to_numpy() resF = pd.read_csv(read_dir / "resF.csv", header=None).to_numpy() X, Y = np.meshgrid(M, D) levels = [0.01] for i in range(25): levels.append(round(1.5 * levels[i], 3)) cf = plt.contourf( X, Y, F, locator=FixedLocator(levels), cmap=plt.get_cmap("Oranges"), norm=LogNorm(vmin=0.01, vmax=100, clip=True), extend="both", ) plt.colorbar(cf, format="%.3f") plt.xlabel("Mass (kg)") plt.ylabel("Damping") plt.scatter(resX[:, 0], resX[:, 1], c="tab:cyan") if Path.exists(read_dir / "knee_points.csv"): knee_points = pd.read_csv(read_dir / "knee_points.csv", header=None).to_numpy() plt.scatter(knee_points[:, 0], knee_points[:, 1], c="tab:blue") # plt.savefig(read_dir / ("heatmap-%s.pdf" % read_dir.name)) plt.show() plt.close()
def plot_stats(names, target_sched, target_ctrl, target_unctrl, sched_ctrl, sched_unctrl, unctrl_ctrl): import matplotlib.pyplot as plt from matplotlib.ticker import FixedLocator fig = plt.figure(figsize=(6.39, 1.75)) fig.subplots_adjust(bottom=0.3) x = np.arange(len(names)) ax0 = fig.add_subplot(111) ax0.set_xlim(-0.5, x[-1] + 0.5) ax0.set_ylim(50, 100) ax0.set_ylabel(r"""Planguete [\%]""", fontsize='small') ax0.grid(False, which='major', axis='x') bars = ax0.bar(x, target_sched, align='center', width=0.5, facecolor=PRIM+(0.5,), edgecolor=EC) autolabel(ax0, bars) # ax1 = fig.add_subplot(212, sharex=ax0) # ax1.set_ylim(50, 100) # ax1.set_ylabel(r"""Erbringung [\%]""", fontsize='small') # ax1.grid(False, which='major', axis='x') # bars = ax1.bar(x, target_ctrl, align='center', width=0.5, facecolor=PRIM+(0.5,), edgecolor=EC) # autolabel(ax1, bars) # plt.setp(ax0.get_xticklabels(), visible=False) ax0.xaxis.set_major_locator(FixedLocator(x)) ax0.set_xticklabels(names, fontsize='xx-small', rotation=45, rotation_mode='anchor', ha='right') return fig
def bar3d(self, **kwargs): #### Not yet ready for primetime from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = Axes3D(fig) plots = [] labels = [] for i, hist in enumerate(self.hists): if self.title is not None: hist.title = self.title if self.xlabel is not None: hist.xlabel = self.xlabel if self.ylabel is not None: hist.ylabel = self.ylabel labels.append(hist.label) all_kwargs = copy.copy(kwargs) all_kwargs.update(self.kwargs[i]) bar = ax.bar(hist.x, hist.y, zs=i, zdir='y', width=hist.width, **all_kwargs) plots.append(bar) from matplotlib.ticker import FixedLocator locator = FixedLocator(range(len(labels))) ax.w_yaxis.set_major_locator(locator) ax.w_yaxis.set_ticklabels(labels) ax.set_ylim3d(-1, len(labels)) return plots
def plot_arg_lengths(cause_lengths, effect_lengths): min_bin, max_bin = 1, 22 bins = range(min_bin, max_bin) bins[-1] -= 0.0001 causes, effects = [list(chain.from_iterable([i] * l[i] for i in bins)) for l in cause_lengths, effect_lengths] cause_y, bin_edges = np.histogram(causes, bins=bins) effect_y, _ = np.histogram(effects, bins=bins) plt.plot(bin_edges[:-1], cause_y, '--', color='#3c6090', marker='o') plt.plot(bin_edges[:-1], effect_y, '-', color='#e84330', marker='s') ax = plt.gca() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) with utopia_context(): plt.tick_params(axis='both', labelsize=11) plt.xlim(0, max_bin - 1.5) # 0 is an uninteresting tick, but 1 is relevant. ax.xaxis.set_major_locator(FixedLocator([1, 5, 10, 15, 20])) plt.xlabel('Argument length (in tokens)', fontsize=13, labelpad=12) plt.ylabel('Count', fontsize=13, labelpad=12) plt.text(2.8, 190, 'Causes', color='#3c6090', fontsize=15) plt.text(7.3, 120, 'Effects', color='#e84330', fontsize=15) plt.tight_layout() fig = plt.gcf() size = fig.get_size_inches() fig.set_size_inches(size[0], size[1] * 0.8) #plt.show(False) plt.savefig('/home/jesse/Documents/Work/Research/My Publications/Thesis/tagging/arg_lengths.pdf')
def silhouette_diag(k, kmeans, X): y_pred = kmeans.labels_ silhouette_coefficients = silhouette_samples(X, y_pred) padding = len(X) // 30 pos = padding ticks = [] for i in range(k): coeffs = silhouette_coefficients[y_pred == i] coeffs.sort() color = mpl.cm.Spectral(i / k) plt.fill_betweenx(np.arange(pos, pos + len(coeffs)), 0, coeffs, facecolor=color, edgecolor=color, alpha=0.9) ticks.append(pos + len(coeffs) // 2) pos += len(coeffs) + padding plt.gca().yaxis.set_major_locator(FixedLocator(ticks)) plt.gca().yaxis.set_major_formatter(FixedFormatter(range(k))) plt.ylabel("Cluster") plt.gca().set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1]) plt.xlabel("Silhouette Coefficient") silhouette_score = silhouette_score(X, kmeans.labels_) plt.axvline(x=silhouette_score, color="red", linestyle="--") plt.title("$k={}$".format(k), fontsize=16) plt.show()
def setup_plot(ax, timestamps, locate_dates, predict_days=PREDICT_DAYS): dates = normalize_dates(timestamps) plt.grid(True, which='both') ax.xaxis.set_major_formatter( FuncFormatter(generate_dates_formatter(timestamps))) ax.xaxis.set_minor_locator(FixedLocator(locate_dates)) plt.xlim(min(dates) - 1, max(dates) + 0.8 * predict_days)
def plot_individual_specific_effects(with_parameters=None): fig, ax = plt.subplots() x = np.linspace(-5, 5, 5000) pdf = ss.norm.pdf(x, 0, 1) ax.plot(x, pdf) ax.set_xlabel(r"$\delta$") ax.set_ylabel("Density") x_formatter = FixedFormatter(["", "", "", 0.5, "", "", ""]) x_locator = FixedLocator([-3, -2, -1, 0, 1, 2, 3]) ax.xaxis.set_major_locator(x_locator) ax.xaxis.set_major_formatter(x_formatter) ax.set_xlim([-3, 3]) ax.set_ylim([0, 0.5]) pos = with_parameters if with_parameters and len(set(pos)) != 1: ax.axvline(x=pos[0], label="ATE", color="red") ax.axvline(x=pos[2], label="ATT", color="orange") ax.axvline(x=pos[1], label="ATC", color="green") ax.legend() elif with_parameters and len(set(pos)) == 1: ax.axvline(x=pos[0], linewidth=3, label="ATE = ATT = ATC", color="red") ax.legend()
def _post_plot_logic(self, ax, data): from matplotlib.ticker import FixedLocator def get_label(i): try: return pprint_thing(data.index[i]) except Exception: return "" if self._need_to_set_index: xticks = ax.get_xticks() xticklabels = [get_label(x) for x in xticks] ax.set_xticklabels(xticklabels) ax.xaxis.set_major_locator(FixedLocator(xticks)) condition = (not self._use_dynamic_x() and data.index.is_all_dates and not self.subplots or (self.subplots and self.sharex)) index_name = self._get_index_name() if condition: # irregular TS rotated 30 deg. by default # probably a better place to check / set this. if not self._rot_set: self.rot = 30 format_date_labels(ax, rot=self.rot) if index_name is not None and self.use_index: ax.set_xlabel(index_name)
def plot_section_by_name(self, section_name, show_data=True, show_faults=True, show_topo=True, show_all_data=False, **kwargs): assert type(section_name) == str, 'section name must be a string of the name of the section' assert self.model.solutions.sections is not None, 'no sections for plotting defined' j = np.where(self.model.grid.sections.names == section_name)[0][0] l0, l1 = self.model.grid.sections.get_section_args(section_name) shape = self.model.grid.sections.resolution[j] image = self.model.solutions.sections[0][l0:l1].reshape(shape[0], shape[1]).T extent = [0, self.model.grid.sections.dist[j][0], self.model.grid.regular_grid.extent[4], self.model.grid.regular_grid.extent[5]] if show_data: self.plot_section_data(section_name=section_name, show_all_data=show_all_data, **kwargs) axes = plt.gca() axes.imshow(image, origin='lower', zorder=-100, cmap=self._cmap, norm=self._norm, extent=extent) if show_faults: self.extract_section_fault_lines(section_name, axes) if show_topo: if self.model.grid.topography is not None: alpha = kwargs.get('alpha', 1) xy = self.make_topography_overlay_4_sections(j) axes.fill(xy[:, 0], xy[:, 1], 'k', zorder=10, alpha=alpha) labels, axname = self._make_section_xylabels(section_name, len(axes.get_xticklabels()) - 2) pos_list = np.linspace(0, self.model.grid.sections.dist[j], len(labels)) axes.xaxis.set_major_locator(FixedLocator(nbins=len(labels), locs=pos_list)) axes.xaxis.set_major_formatter(FixedFormatter((labels))) axes.set(title=self.model.grid.sections.names[j], xlabel=axname, ylabel='Z')
def update_figure(self, canvas_price_out, interval): start_date_index = self.calculate_start_date_index(interval) x_unit = range(0, len(self.num_date_list[start_date_index:])) self.axes.cla() if canvas_price_out: self.canvas_y_list = self.price_out_list[start_date_index:] self.axes.set_title('Bank Selling Price') self.axes.plot(x_unit, self.canvas_y_list, 'r', color='#B99A1D') self.axes.patch.set_facecolor('#E3F0FD') self.fig.set_facecolor('#CBD7E6') else: self.canvas_y_list = self.price_in_list[start_date_index:] self.axes.set_title('Bank Buying Price') self.axes.plot(x_unit, self.canvas_y_list, 'r', color='#FF53D5') self.axes.patch.set_facecolor('#FFECFF') self.fig.set_facecolor('#FFC8FF') self.canvas_x_list = self.num_date_list[start_date_index:] self.canvas_x_str_list = miner.datetime_to_str(self.canvas_x_list) index_list = miner.get_first_date_index_in_month( self.num_date_list[start_date_index:]) self.axes.axis( [0, len(self.num_date_list[start_date_index:]) - 1, None, None]) self.axes.xaxis.set_major_locator(FixedLocator(index_list)) self.axes.xaxis.set_major_formatter( IndexDateFormatter(date2num(self.num_date_list[start_date_index:]), '%b')) self.draw()
def render_figure(chart_title, xvals, yvals): print "Now rendering figure..." fig = figure() ax1 = fig.add_subplot(111) # ax1.step(xvals, yvals, linewidth=2.0, marker=".", linestyle="-") ax1.fill_between(xvals, 0, yvals, linewidth=0, facecolor='blue', alpha=0.3) def mjrFormatter(x, pos): if x == 1: return "On" elif x == 0: return "Off" else: return "" ax1.grid(False) ax1.set_xlabel('Time') ax1.set_ylabel('Connection Status') ax1.set_ylim([0,1.5]) ax1.set_title(chart_title) ax1.xaxis.set_major_formatter(DateFormatter('%a %b %d, %I:%M %P')) ax1.yaxis.set_major_formatter(FuncFormatter(mjrFormatter)) ax1.yaxis.set_major_locator(FixedLocator([0, 1])) fig.autofmt_xdate() ax1.autoscale_view() return fig
def map_common(ax1, gl_loc=[True, True, False, True], gl_lon_info=range(-180, 180, 60), gl_dlat=30): ax1.coastlines(color='silver', linewidth=1.) gl = ax1.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.6, color='gray', alpha=0.5, linestyle='--') gl.ylabels_left = gl_loc[0] gl.ylabels_right = gl_loc[1] gl.xlabels_top = gl_loc[2] gl.xlabels_bottom = gl_loc[3] gl.xlocator = FixedLocator(gl_lon_info) gl.ylocator = MultipleLocator(gl_dlat) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 11, 'color': 'k'} gl.ylabel_style = {'size': 11, 'color': 'k'}
def _print_hits(self, pattern_index, hit_list, humanisation, pattern_length=1): #X represents the data points to be plotted on the grid. #It also stores velocity data about each hit. X = np.zeros((4, 16 * pattern_length)) #iterator j = 0 for i in hit_list: if i[0] == 'k': X[3][int(i[1]) - 1] = 1. / (self.volume - abs(humanisation[j]) * 300) if i[0] == 's': X[2][int(i[1]) - 1] = 1. / (self.volume - abs(humanisation[j]) * 300) if i[0] == 'g': X[2][int(i[1]) - 1] = 1. / (40 - abs(humanisation[j]) * 300) if i[0] == 'h': X[1][int(i[1]) - 1] = 1. / (self.volume - abs(humanisation[j]) * 300) if i[0] == 'p': X[0][int(i[1]) - 1] = 1. / (self.volume - abs(humanisation[j]) * 300) j += 1 #Normalise zero values for heat mapping purposes. normal_value = np.amax(X) + 0.005 X[X == 0] = normal_value #Plot figure. fig, ax = plt.subplots(figsize=(10, 10)) ax.imshow(X, cmap=plt.get_cmap('gist_gray')) y_labels = ['Percussion', 'Hat', 'Snare', 'Kick'] ax.set_xticks(list(range(0, 16 * pattern_length))) ax.set_yticks(list(range(0, 4))) ax.set_yticklabels(y_labels) ax.set_xticklabels(list(range(1, 16 * pattern_length + 1))) minor_xlocator = AutoMinorLocator(2) minor_ylocator = FixedLocator( [x + 0.5 for x in range(0, 16 * pattern_length)]) ax.xaxis.set_minor_locator(minor_xlocator) ax.yaxis.set_minor_locator(minor_ylocator) ax.grid(which='minor', color='0.4', linestyle='dashed') fig.patch.set_facecolor("None") canvas = FigureCanvas(fig) canvas.setStyleSheet("background-color:transparent;") canvas.draw() return canvas
def format_xaxis(self, **kwargs): """ Formats the x axis. """ self.xaxis.set_major_locator(FixedLocator(self.positions)) self.set_xticklabels(self.periodlabels, **kwargs) self.set_xlim((-1, len(self.positions) + 1))
def map_common(ax1, gl_loc=[True, True, False, True], gl_dlon=60, gl_dlat=30): ax1.set_title(subtit, x=0., ha='left', fontsize=13, stretch='semi-condensed') ax1.coastlines(color='silver', linewidth=1.) gl = ax1.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.6, color='gray', alpha=0.5, linestyle='--') gl.ylabels_left = gl_loc[0] gl.ylabels_right = gl_loc[1] gl.xlabels_top = gl_loc[2] gl.xlabels_bottom = gl_loc[3] gl.xlocator = FixedLocator( range(-180 + gl_dlon, 361, gl_dlon)) #[0,60,180,240,360]) #np.arange(-180,181,60)) gl.ylocator = MultipleLocator(gl_dlat) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 11, 'color': 'k'} gl.ylabel_style = {'size': 11, 'color': 'k'}
def set_default_locators_and_formatters(self, axis): """ Override to set up the locators and formatters to use with the scale. This is only required if the scale requires custom locators and formatters. Writing custom locators and formatters is rather outside the scope of this example, but there are many helpful examples in ``ticker.py``. In our case, the Mercator example uses a fixed locator from -90 to 90 degrees and a custom formatter class to put convert the radians to degrees and put a degree symbol after the value:: """ #class DegreeFormatter(Formatter): # def __call__(self, x, pos=None): # # \u00b0 : degree symbol # return "%d\u00b0" % ((x / np.pi) * 180.0) #axis.set_major_locator(MaxNLocator(10)) ticks = None for k in range(1, len(self.zval)): nbins = 16 * (self.zfrac[k] - self.zfrac[k - 1]) newticks = MaxNLocator(nbins=nbins, steps=[1, 2, 2.5, 5, 10]).tick_values( self.zval[k - 1], self.zval[k]) if ticks == None: ticks = newticks else: ticks = np.append(ticks, newticks) ticks = [ x for x in ticks if (x > +self.zval.min() and x <= self.zval.max()) ] # Only used tickes within range ticks = np.sort( ticks ) # Fix due to different python versions on PP and workstations! axis.set_major_locator(FixedLocator(ticks))
def plot_knife(plt, data, group_column='group', value_column_format="group{}_proba"): padding = len(data) // 30 pos = padding ticks = [] groups = data[group_column].unique() length = len(groups) for i in groups: color = mpl.cm.Spectral(i / length) column_name = value_column_format.format(i) values = data.loc[( data[group_column] == i)][column_name].sort_values().values plt.fill_betweenx(np.arange(pos, pos + len(values)), 0, values, facecolor=color, edgecolor=color, alpha=0.7) ticks.append(pos + len(values) // 2) pos += len(values) + padding plt.gca().yaxis.set_major_locator(FixedLocator(ticks)) plt.gca().yaxis.set_major_formatter(FixedFormatter(groups)) plt.axvline(x=0.5, color="red", linestyle="--")
def show_result(ac_score_list,dataset_name): plot_spc = [5, 10] left_spc = 1 len_params = 295 use_arr = ac_score_list[left_spc:int((len_params - plot_spc[0]) / plot_spc[1])] ax = plt.subplot() ax.plot(np.arange(plot_spc[0] + plot_spc[1] * left_spc, len_params, plot_spc[1]), use_arr, '-o', label='AFS') plt.title(dataset_name) plt.ylabel('Accuracy') plt.xlabel('K') plt.ylim(0.0, 1.0) xmajorLocator = FixedLocator([15, 85, 155, 225, 295]) xminorLocator = MultipleLocator(5) ax.xaxis.set_major_locator(xmajorLocator) ax.xaxis.set_minor_locator(xminorLocator) ax.xaxis.grid(True, which='minor') ymajorLocator = MultipleLocator(0.1) ax.yaxis.set_major_locator(ymajorLocator) ax.yaxis.grid(True, which='major') box = ax.get_position() ax.set_position([box.x0, box.y0, box.width, box.height * 0.8]) plt.show()
def plot_mult_timetrends(data, geoids, cols, area, colors, markers, sharex, ylim_bottom = -150, ylim_top = 150, ylabel = 'Pct change in mobility', xlabels=None): """outputs four timeseries, layered, using inputted vector of colors """ ax = plt.axes(area, sharex = None) cols = cols plt.hlines(0,data.num_date.min(),data.num_date.max()) i = 0 for y in cols: pts = y[:12] # lim = ylim # plt.xlabel('date', fontsize=18) plt.ylabel(ylabel, fontsize=22) plt.yticks(fontsize=30) x_locator = FixedLocator(data.num_date[np.arange(0,data.shape[0],7)].tolist()) ax.xaxis.set_minor_locator(x_locator) plt.grid(axis='x', which = 'both') plt.plot(data['num_date'], data[y], color = colors[i], linewidth=5) i = i+ 1 plt.xticks(ticks = data.num_date[np.arange(0,data.shape[0],28)].tolist(), labels = xlabels, rotation=30, ha='right', fontsize=30) plt.ylim(ylim_bottom,ylim_top) return ax
def _set_scale(self): """ Check if parent has set its scale """ if self._orientation == 'x': pscale = self._parent.xaxis.get_scale() set_scale = self.set_xscale if self._orientation == 'y': pscale = self._parent.yaxis.get_scale() set_scale = self.set_yscale if pscale == 'log': defscale = 'functionlog' else: defscale = 'function' if self._ticks_set: ticks = self._axis.get_ticklocs() set_scale(defscale, functions=self._functions) # OK, set_scale sets the locators, but if we've called # axsecond.set_ticks, we want to keep those. if self._ticks_set: self._axis.set_major_locator(FixedLocator(ticks))
def plotTiming(vortex_prob, vortex_times, times, map, grid_spacing, tornado_track, title, file_name, obs=None, centers=None, min_prob=0.1): nx, ny = vortex_prob.shape gs_x, gs_y = grid_spacing xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny)) time_color_map = matplotlib.cm.Accent time_color_map.set_under('#ffffff') vortex_times = np.where(vortex_prob >= min_prob, vortex_times, -1) track_xs, track_ys = map(*reversed(tornado_track)) pylab.figure(figsize=(10, 8)) pylab.axes((0.025, 0.025, 0.95, 0.925)) pylab.pcolormesh(xs, ys, vortex_times, cmap=time_color_map, vmin=times.min(), vmax=times.max()) tick_labels = [ (datetime(2009, 6, 5, 18, 0, 0) + timedelta(seconds=int(t))).strftime("%H%M") for t in times ] bar = pylab.colorbar()#orientation='horizontal', aspect=40) bar.locator = FixedLocator(times) bar.formatter = FixedFormatter(tick_labels) bar.update_ticks() pylab.plot(track_xs, track_ys, 'mv-', lw=2.5, mfc='k', ms=8) drawPolitical(map, scale_len=(xs[-1, -1] - xs[0, 0]) / 10.) pylab.title(title) pylab.savefig(file_name) pylab.close()
def plot_silhouette_histogram(X): from sklearn.metrics import silhouette_samples from matplotlib.ticker import FixedLocator, FixedFormatter import matplotlib as mpl import numpy as np silhouette_scores = [] from sklearn.metrics import silhouette_score for i in range(20)[2:]: km = KMeans(n_clusters=i) km.fit_predict(X) silhouette_scores.append(silhouette_score(X, km.labels_)) print "begin to plot silhouette histogram... silhouette_scores:{}".format( silhouette_scores) kmeans_per_k = [ KMeans(n_clusters=k, random_state=42).fit(X) for k in range(1, 30) ] inertias = [model.inertia_ for model in kmeans_per_k] plt.figure(figsize=(10, 5)) for k in (12, 13, 14, 15): plt.subplot(2, 2, k - 11) y_pred = kmeans_per_k[k - 1].labels_ silhouette_coefficients = silhouette_samples(X, y_pred) padding = len(X) // 30 pos = padding ticks = [] for i in range(k): coeffs = silhouette_coefficients[y_pred == i] coeffs.sort() color = mpl.cm.Spectral(i / k) plt.fill_betweenx(np.arange(pos, pos + len(coeffs)), 0, coeffs, facecolor=color, edgecolor=color, alpha=0.7) ticks.append(pos + len(coeffs) // 2) pos += len(coeffs) + padding plt.gca().yaxis.set_major_locator(FixedLocator(ticks)) plt.gca().yaxis.set_major_formatter(FixedFormatter(range(k))) if k in (12, 14): plt.ylabel("Cluster") if k in (14, 15): plt.gca().set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1]) plt.xlabel("Silhouette Coefficient") else: plt.tick_params(labelbottom=False) plt.axvline(x=silhouette_scores[k - 2], color="red", linestyle="--") plt.title("$k={}$".format(k), fontsize=16) plt.show()
def scattercheck(self, parsamples, output, ncols=3, *args, **kwargs): ''' Plot the parvalues against one outputs of the model to evaluate the linearity of the relationship between the parameter and the output and to get a general idea of the model behavior towards this output. Is a useful and practical visualisation for all methods, but essential when useing the regression based method to check for linearity/monotonicity. Parameters ----------- parsamples : ndarray array with the sampled parameter values output : 1D ndarray array with the output values for these parameter combinations ncols : int number of columns to put subplots in *args, **kwargs : scatter options given tot the different scatter-subplots ''' #control if output only has one col if output.size != output.shape[0]: raise Exception('Choose a single output to plot') #define number of rows numpars = parsamples.shape[1] nrows = np.divide(numpars, ncols) if np.remainder(numpars, ncols)>0: nrows += 1 #prepare plots fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,12)) fig.subplots_adjust(hspace=0.25, wspace=0.02) i = 0 for ax in axes.flat: #x0,x1 = ax.get_xlim() #y0,y1 = ax.get_ylim() #ax.set_aspect((x1-x0)/(y1-y0)) if i < numpars: ax.scatter(parsamples[:, i], output, *args, **kwargs) ax.set_title(self._namelist[i]) #adjust ticks majorlocator = FixedLocator([self._parsin[i][0], self._parsin[i][1]]) ax.xaxis.set_major_locator(majorlocator) if ax.is_first_col(): majloc1 = MaxNLocator(nbins = 4) ax.yaxis.set_major_locator(majloc1) else: plt.setp(ax.get_yticklabels(), visible = False) else: ax.set_axis_off() i += 1 return fig, axes
def main(ctl_fname, amb_fname, case_name): df_a = read_cable_file(ctl_fname) df_a = resample_to_seasonal_cycle(df_a) df_e = read_cable_file(amb_fname) df_e = resample_to_seasonal_cycle(df_e) fig = plt.figure(figsize=(8, 6)) fig.subplots_adjust(hspace=0.3) fig.subplots_adjust(wspace=0.2) plt.rcParams['text.usetex'] = False plt.rcParams['font.family'] = "sans-serif" plt.rcParams['font.sans-serif'] = "Helvetica" plt.rcParams['axes.labelsize'] = 12 plt.rcParams['font.size'] = 12 plt.rcParams['legend.fontsize'] = 12 plt.rcParams['xtick.labelsize'] = 12 plt.rcParams['ytick.labelsize'] = 12 ax1 = fig.add_subplot(3, 2, 1) ax2 = fig.add_subplot(3, 2, 2) ax3 = fig.add_subplot(3, 2, 3) ax4 = fig.add_subplot(3, 2, 4) ax5 = fig.add_subplot(3, 2, 5) ax6 = fig.add_subplot(3, 2, 6) axes = [ax1, ax2, ax3, ax4, ax5, ax6] vars = ["GPP", "CO2air", "Qle", "LAI", "TVeg", "ESoil"] for a, v in zip(axes, vars): a.plot(df_a.month, df_a[v], c="blue", lw=2.0, ls="-", label="hyds") a.plot(df_e.month, df_e[v], c="red", lw=2.0, ls="-", label=case_name) labels = ["GPP (g C m$^{-2}$ d$^{-1}$)", \ "CO$_2$ ($\mathrm{\mu}$mol mol$^{-1}$)",\ "Qle (W m$^{-2}$)", "LAI (m$^{2}$ m$^{-2}$)",\ "TVeg (mm d$^{-1}$)", "Esoil (mm d$^{-1}$)"] for a, l in zip(axes, labels): a.set_title(l, fontsize=12) xtickagaes_minor = FixedLocator([2, 3, 4, 5, 7, 8, 9, 10, 11]) for i, a in enumerate(axes): a.set_xticks([1, 6, 12]) if i != 1: a.set_ylim(ymin=0) a.xaxis.set_minor_locator(xtickagaes_minor) a.set_xticklabels(['Jan', 'Jun', 'Dec']) if i < 4: plt.setp(a.get_xticklabels(), visible=False) ax1.legend(numpoints=1, loc="best") plot_fname = "seasonal_plot_gw_on_or_on_hyds_test_31layers_%s.png" % ( case_name) plot_dir = "plots" if not os.path.exists(plot_dir): os.makedirs(plot_dir) fig.savefig(os.path.join(plot_dir, plot_fname), bbox_inches='tight', pad_inches=0.1)
def set_default_locators_and_formatters(self, axis): axis.set_major_locator( FixedLocator( np.array([1 - 10**(-k) for k in range(1 + self.nines)]))) axis.set_major_formatter( FixedFormatter([ str(100 * (1 - 10**(-k))) + "%" for k in range(1 + self.nines) ]))
def pylab_axis(self, ax): from matplotlib.ticker import FixedLocator if np.all(self.widths == 1): ax.xaxis.set_tick_params(which='major', length=0) x = self.pcenters else: x = self.bins ax.xaxis.set_minor_locator(FixedLocator(self.pedges)) if self.pedges.size > 10: xi = list(range(0, int(0.9 * len(x)), max( 1, len(x) // 5))) + [len(x) - 1] else: xi = range(len(x)) ax.xaxis.set_major_locator(FixedLocator(x[xi]))