def set_default_locators_and_formatters(self, axis): axis.set_major_locator(LogLocator(self.base)) axis.set_major_formatter(GWpyLogFormatterMathtext(self.base)) axis.set_minor_locator(LogLocator(self.base, self.subs)) axis.set_minor_formatter(MinorLogFormatterMathtext(self.base))
label=location, c="k") plt.ylim(bottom=1) plt.semilogy() plt.xlabel("Time") plt.ylabel("Case increase") from matplotlib.dates import AutoDateLocator, DateFormatter from matplotlib.ticker import LogLocator, NullLocator, LogFormatter from util import LogFormatterSI import numpy plt.gca().xaxis.set_major_locator(AutoDateLocator()) plt.gca().xaxis.set_major_formatter(DateFormatter("%m/%d")) plt.gca().xaxis.set_minor_locator(AutoDateLocator()) plt.gca().yaxis.set_major_locator(LogLocator(subs=(1, 2, 5))) plt.gca().yaxis.set_major_formatter( LogFormatterSI(labelOnlyBase=False, minor_thresholds=(numpy.inf, numpy.inf))) plt.gca().yaxis.set_minor_locator(NullLocator()) plt.title("New York State COVID-19 daily case increase (approx.)") #plt.xlim(left=arrow.get("2020-03-01")) #plt.ylim(bottom=10) plt.legend() plt.savefig("plots/rate_nys.png")
def plot_bias_density(exp_df, plot_dir): exp_df = exp_df.replace([np.inf, -np.inf], np.nan) exp_df = exp_df.dropna() plt.figure(figsize=(15, 15)) grid = plt.GridSpec(2, 1, hspace=0.3, wspace=0.2) ax2 = plt.subplot(grid[0]) ax1 = plt.subplot(grid[1]) cmap = plt.get_cmap("tab10") for i, temp_bias in enumerate(np.sort(exp_df.temp_bias.unique())): j = i if i >= 3: j = j + 1 # Subset to the airline subset = exp_df[exp_df['temp_bias'] == temp_bias] # Draw the density plot sns.distplot(subset['bias'], hist=False, kde=True, kde_kws={ 'shade': True, 'linewidth': 3, 'alpha': 0.15 }, bins=30, ax=ax2) ax2.plot(ax2.lines[-1].get_xydata()[:, 0], ax2.lines[-1].get_xydata()[:, 1], color=cmap(j), label=temp_bias) ax2.axvline(x=subset.bias.mean(), color=cmap(j), linestyle=':') exp_df.area_diff.plot.hist(ax=ax1, bins=50) ax1.set_yscale('log') # ax1.set_xscale('symlog',linthreshx=1e-2) ax1.set_ylabel('Frequency', labelpad=30) ax1.set_xlabel(r'Area difference (km$^2$)') ax1.set_xlim(-1.05, 1.05) ax2.set_ylim(0, None) ax2.set_yticks([0, 1e-3, 2e-3]) ax2.set_xticks(np.arange(-1500, 2000, 500)) from matplotlib.ticker import LogLocator ax1.yaxis.set_minor_locator(LogLocator(base=10, subs='auto')) ax1.tick_params(which='major', length=6, width=3) ax1.tick_params(which='minor', length=4, color='k', width=2) add_at(ax2, 'a') add_at(ax1, 'b') ax1.grid() ax2.grid() ax2.set_xlabel( r'Optimal mass balance balance bias $\beta^*_{mb}$ (mm w.e.)') ax2.set_ylabel('Density') ax2.legend(title=r'temp. bias $\widetilde{\beta}$') plt.savefig(os.path.join(plot_dir, 'mb_bias.png'), dpi=300) plt.show()
upper_new_interp(mvals2), alpha=0.4, color='DarkBlue', edgecolor='black') ax1.fill_between(mvals5, upper_old_interp(mvals5), 10**upper_new_nucleus_interp(np.log10(mvals5)), alpha=0.4, color='DarkRed', edgecolor='black') ax1.set_ylim(1e-47, 1e-17) ax1.set_xlabel(r"DM mass $m_\chi \,\,[\mathrm{GeV}]$") ax1.set_ylabel( r"DM-nucleon cross section $\sigma_p^\mathrm{SI}\,\,[\mathrm{cm}^2]$") ax1.xaxis.set_minor_locator(LogLocator(base=10.0, subs=(10, ))) ax1.yaxis.set_minor_locator(LogLocator(base=10.0, subs=(10, 100, 1000))) txtfont = 12.0 ax1.text(10, 1e-19, "High-altitude", color='DarkOrange', fontsize=txtfont) ax1.text(1e6, 1e-35, "Direct detection", fontsize=txtfont) ax1.text(1e4, 1e-45, "Xenon1T", fontsize=txtfont) ax1.text(1e0, 1e-38, "CRESST-III", fontsize=txtfont) #ax1.text(5e-2, 1e-26, "CRESST 2017\nsurface",fontsize=txtfont) ax1.text(1e6, 1e-21, "CDMS-I (this work)", color='DarkBlue', fontsize=txtfont) ax1.text(0.5e1, 0.3e-25, "CRESST 2017 surface\n(this work)", color='Red', fontsize=txtfont)
def __decorate_axis(axis, ax_type): '''Configure axis tickers, locators, and labels''' if ax_type == 'tonnetz': axis.set_major_formatter(TonnetzFormatter()) axis.set_major_locator(FixedLocator(0.5 + np.arange(6))) axis.set_label_text('Tonnetz') elif ax_type == 'chroma': axis.set_major_formatter(ChromaFormatter()) axis.set_major_locator( FixedLocator(0.5 + np.add.outer(12 * np.arange(10), [0, 2, 4, 5, 7, 9, 11]).ravel())) axis.set_label_text('Pitch class') elif ax_type == 'tempo': axis.set_major_formatter(ScalarFormatter()) axis.set_major_locator(LogLocator(base=2.0)) axis.set_label_text('BPM') elif ax_type == 'time': axis.set_major_formatter(TimeFormatter(lag=False)) axis.set_major_locator( MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10])) axis.set_label_text('Time') elif ax_type == 'lag': axis.set_major_formatter(TimeFormatter(lag=True)) axis.set_major_locator( MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10])) axis.set_label_text('Lag') elif ax_type == 'cqt_note': axis.set_major_formatter(NoteFormatter()) axis.set_major_locator(LogLocator(base=2.0)) axis.set_minor_formatter(NoteFormatter(major=False)) axis.set_minor_locator( LogLocator(base=2.0, subs=2.0**(np.arange(1, 12) / 12.0))) axis.set_label_text('Note') elif ax_type in ['cqt_hz']: axis.set_major_formatter(LogHzFormatter()) axis.set_major_locator(LogLocator(base=2.0)) axis.set_minor_formatter(LogHzFormatter(major=False)) axis.set_minor_locator( LogLocator(base=2.0, subs=2.0**(np.arange(1, 12) / 12.0))) axis.set_label_text('Hz') elif ax_type in ['mel', 'log']: axis.set_major_formatter(ScalarFormatter()) axis.set_major_locator(SymmetricalLogLocator(axis.get_transform())) axis.set_label_text('Hz') elif ax_type in ['linear', 'hz']: axis.set_major_formatter(ScalarFormatter()) axis.set_label_text('Hz') elif ax_type in ['frames']: axis.set_label_text('Frames') elif ax_type in ['off', 'none', None]: axis.set_label_text('') axis.set_ticks([])
def plot_objective( result, levels=20, n_points=200, n_samples=30, size=3, zscale="linear", dimensions=None, plot_standard_deviation=False, n_random_restarts=100, alpha=0.25, margin=0.65, colors=None, fig=None, ax=None, ): """Pairwise partial dependence plot of the objective function. The diagonal shows the partial dependence for dimension `i` with respect to the objective function. The off-diagonal shows the partial dependence for dimensions `i` and `j` with respect to the objective function. The objective function is approximated by `result.model.` Pairwise scatter plots of the points at which the objective function was directly evaluated are shown on the off-diagonal. A red point indicates the found minimum. Note: search spaces that contain `Categorical` dimensions are currently not supported by this function. Parameters ---------- * `result` [`OptimizeResult`] The result for which to create the scatter plot matrix. * `levels` [int, default=10] Number of levels to draw on the contour plot, passed directly to `plt.contour()`. * `n_points` [int, default=40] Number of points at which to evaluate the partial dependence along each dimension. * `n_samples` [int, default=250] Number of random samples to use for averaging the model function at each of the `n_points`. * `size` [float, default=2] Height (in inches) of each facet. * `zscale` [str, default='linear'] Scale to use for the z axis of the contour plots. Either 'linear' or 'log'. * `dimensions` [list of str, default=None] Labels of the dimension variables. `None` defaults to `space.dimensions[i].name`, or if also `None` to `['X_0', 'X_1', ..]`. * `n_random_restarts` [int, default=100] Number of restarts to try to find the global optimum. * `alpha` [float, default=0.25] Transparency of the sampled points. * `margin` [float, default=0.65] Margin in inches around the plot. * `colors` [list of tuples, default=None] Colors to use for the optima. * `fig` [Matplotlib figure, default=None] Figure to use for plotting. If None, it will create one. * `ax` [k x k axes, default=None] Axes on which to plot the marginals. If None, it will create appropriate axes. Returns ------- * `ax`: [`Axes`]: The matplotlib axes. """ if colors is None: colors = plt.cm.get_cmap("Set3").colors space = result.space contour_plot = np.empty((space.n_dims, space.n_dims), dtype=object) samples = np.asarray(result.x_iters) rvs_transformed = space.transform(space.rvs(n_samples=n_samples)) z_min = np.full((space.n_dims, space.n_dims), np.inf) z_max = np.full((space.n_dims, space.n_dims), np.NINF) z_ranges = np.zeros((space.n_dims, space.n_dims)) if zscale == "log": locator = LogLocator() elif zscale == "linear": locator = None else: raise ValueError("Valid values for zscale are 'linear' and 'log'," " not '%s'." % zscale) if fig is None: fig, ax = plt.subplots( space.n_dims, space.n_dims, figsize=(size * space.n_dims, size * space.n_dims), ) width, height = fig.get_size_inches() fig.subplots_adjust( left=margin / width, right=1 - margin / width, bottom=margin / height, top=1 - margin / height, hspace=0.1, wspace=0.1, ) failures = 0 while True: try: with result.models[-1].noise_set_to_zero(): min_x = expected_ucb(result, alpha=0.0, n_random_starts=n_random_restarts)[0] min_ucb = expected_ucb(result, n_random_starts=n_random_restarts)[0] except ValueError: failures += 1 if failures == 10: break continue else: break for i in range(space.n_dims): for j in range(space.n_dims): if i == j: xi, yi = partial_dependence( space, result.models[-1], i, j=None, plot_standard_deviation=plot_standard_deviation, sample_points=rvs_transformed, n_points=n_points, ) yi_min, yi_max = np.min(yi), np.max(yi) ax[i, i].plot(xi, yi, color=colors[1]) if failures != 10: ax[i, i].axvline(min_x[i], linestyle="--", color=colors[3], lw=1) ax[i, i].axvline(min_ucb[i], linestyle="--", color=colors[5], lw=1) ax[i, i].text( min_x[i], yi_min + 0.9 * (yi_max - yi_min), f"{np.around(min_x[i], 4)}", color=colors[3], ) ax[i, i].text( min_ucb[i], yi_min + 0.7 * (yi_max - yi_min), f"{np.around(min_ucb[i], 4)}", color=colors[5], ) # lower triangle elif i > j: xi, yi, zi = partial_dependence( space, result.models[-1], i, j, plot_standard_deviation, rvs_transformed, n_points, ) contour_plot[i, j] = ax[i, j].contourf(xi, yi, zi, levels, locator=locator, cmap="viridis_r") #fig.colorbar(contour_plot[i, j], ax=ax[i, j]) ax[i, j].scatter(samples[:, j], samples[:, i], c="k", s=10, lw=0.0, alpha=alpha) if failures != 10: ax[i, j].scatter(min_x[j], min_x[i], c=["r"], s=20, lw=0.0) ax[i, j].scatter(min_ucb[j], min_ucb[i], c=["xkcd:orange"], s=20, lw=0.0) z_min[i, j] = np.min(zi) z_max[i, j] = np.max(zi) z_ranges[i, j] = np.max(zi) - np.min(zi) ax[i, j].text( 0.5, 0.5, np.format_float_positional( z_ranges[i, j], precision=2, unique=False, fractional=False, trim="k", ), horizontalalignment="center", verticalalignment="center", transform=ax[i, j].transAxes, ) # Get all dimensions. plot_dims = [] for row in range(space.n_dims): if space.dimensions[row].is_constant: continue plot_dims.append((row, space.dimensions[row])) for i in range(space.n_dims): for j in range(space.n_dims): if i > j: contour_plot[i, j].set_clim(vmin=np.min(z_min), vmax=np.max(z_max)) fig.colorbar( plt.cm.ScalarMappable( norm=matplotlib.colors.Normalize(vmin=np.min(z_min), vmax=np.max(z_max)), cmap="viridis_r", ), ax=ax[np.triu_indices(space.n_dims, k=1)], shrink=0.7, ) #plt.cm.ScalarMappable.set_clim(self, vmin=np.min(z_min), vmax=np.max(z_max)) #fig.colorbar(contour_plot[1, 0], ax=ax[np.triu_indices(space.n_dims, k=1)]) if plot_standard_deviation: return _format_scatter_plot_axes( ax, space, ylabel="Standard deviation", plot_dims=plot_dims, dim_labels=dimensions, ) else: return _format_scatter_plot_axes( ax, space, ylabel="Partial dependence", plot_dims=plot_dims, dim_labels=dimensions, )
def plot_density(xall, yall, ax=None, cmap=None, ncontours=100, vmin=None, vmax=None, levels=None, cbar=True, cax=None, cbar_label='sample density', cbar_orientation='vertical', logscale=False, nbins=100, weights=None, avoid_zero_count=False, **kwargs): """Plot a two-dimensional density map using a histogram of scattered data. Parameters ---------- xall : ndarray(T) Sample x-coordinates. yall : ndarray(T) Sample y-coordinates. ax : matplotlib.Axes object, optional, default=None The ax to plot to; if ax=None, a new ax (and fig) is created. cmap : matplotlib colormap, optional, default=None The color map to use. ncontours : int, optional, default=100 Number of contour levels. vmin : float, optional, default=None Lowest z-value to be plotted. vmax : float, optional, default=None Highest z-value to be plotted. levels : iterable of float, optional, default=None Contour levels to plot. cbar : boolean, optional, default=True Plot a color bar. cax : matplotlib.Axes object, optional, default=None Plot the colorbar into a custom axes object instead of stealing space from ax. cbar_label : str, optional, default='sample density' Colorbar label string; use None to suppress it. cbar_orientation : str, optional, default='vertical' Colorbar orientation; choose 'vertical' or 'horizontal'. logscale : boolean, optional, default=False Plot the z-values in logscale. nbins : int, optional, default=100 Number of histogram bins used in each dimension. weights : ndarray(T), optional, default=None Sample weights; by default all samples have the same weight. avoid_zero_count : bool, optional, default=True Avoid zero counts by lifting all histogram elements to the minimum value before computing the free energy. If False, zero histogram counts would yield infinity in the free energy. Optional parameters for contourf (**kwargs) ------------------------------------------- corner_mask : boolean, optional Enable/disable corner masking, which only has an effect if z is a masked array. If False, any quad touching a masked point is masked out. If True, only the triangular corners of quads nearest those points are always masked out, other triangular corners comprising three unmasked points are contoured as usual. Defaults to rcParams['contour.corner_mask'], which defaults to True. alpha : float The alpha blending value. locator : [ None | ticker.Locator subclass ] If locator is None, the default MaxNLocator is used. The locator is used to determine the contour levels if they are not given explicitly via the levels argument. extend : [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] Unless this is ‘neither’, contour levels are automatically added to one or both ends of the range so that all data are included. These added ranges are then mapped to the special colormap values which default to the ends of the colormap range, but can be set via matplotlib.colors.Colormap.set_under() and matplotlib.colors.Colormap.set_over() methods. xunits, yunits : [ None | registered units ] Override axis units by specifying an instance of a matplotlib.units.ConversionInterface. antialiased : boolean, optional Enable antialiasing, overriding the defaults. For filled contours, the default is True. For line contours, it is taken from rcParams[‘lines.antialiased’]. nchunk : [ 0 | integer ] If 0, no subdivision of the domain. Specify a positive integer to divide the domain into subdomains of nchunk by nchunk quads. Chunking reduces the maximum length of polygons generated by the contouring algorithm which reduces the rendering workload passed on to the backend and also requires slightly less RAM. It can however introduce rendering artifacts at chunk boundaries depending on the backend, the antialiased flag and value of alpha. hatches : A list of cross hatch patterns to use on the filled areas. If None, no hatching will be added to the contour. Hatching is supported in the PostScript, PDF, SVG and Agg backends only. zorder : float Set the zorder for the artist. Artists with lower zorder values are drawn first. Returns ------- fig : matplotlib.Figure object The figure in which the used ax resides. ax : matplotlib.Axes object The ax in which the map was plotted. misc : dict Contains a matplotlib.contour.QuadContourSet 'mappable' and, if requested, a matplotlib.Colorbar object 'cbar'. """ x, y, z = get_histogram(xall, yall, nbins=nbins, weights=weights, avoid_zero_count=avoid_zero_count) pi = _to_density(z) pi = _np.ma.masked_where(pi <= 0, pi) if logscale: from matplotlib.colors import LogNorm norm = LogNorm(vmin=vmin, vmax=vmax) if levels is None: levels = _np.logspace(_np.floor(_np.log10(pi.min())), _np.ceil(_np.log10(pi.max())), ncontours + 1) else: norm = None fig, ax, misc = plot_map(x, y, pi, ax=ax, cmap=cmap, ncontours=ncontours, vmin=vmin, vmax=vmax, levels=levels, cbar=cbar, cax=cax, cbar_label=cbar_label, cbar_orientation=cbar_orientation, norm=norm, **kwargs) if cbar and logscale: from matplotlib.ticker import LogLocator misc['cbar'].set_ticks(LogLocator(base=10.0, subs=range(10))) return fig, ax, misc
def __decorate_axis(axis, ax_type, key="C:maj", Sa=None, mela=None, thaat=None, unicode=True): """Configure axis tickers, locators, and labels""" if ax_type == "tonnetz": axis.set_major_formatter(TonnetzFormatter()) axis.set_major_locator(FixedLocator(np.arange(6))) axis.set_label_text("Tonnetz") elif ax_type == "chroma": axis.set_major_formatter(ChromaFormatter(key=key, unicode=unicode)) degrees = core.key_to_degrees(key) axis.set_major_locator( FixedLocator(np.add.outer(12 * np.arange(10), degrees).ravel())) axis.set_label_text("Pitch class") elif ax_type == "chroma_h": if Sa is None: Sa = 0 axis.set_major_formatter(ChromaSvaraFormatter(Sa=Sa, unicode=unicode)) if thaat is None: # If no thaat is given, show all svara degrees = np.arange(12) else: degrees = core.thaat_to_degrees(thaat) # Rotate degrees relative to Sa degrees = np.mod(degrees + Sa, 12) axis.set_major_locator( FixedLocator(np.add.outer(12 * np.arange(10), degrees).ravel())) axis.set_label_text("Svara") elif ax_type == "chroma_c": if Sa is None: Sa = 0 axis.set_major_formatter( ChromaSvaraFormatter(Sa=Sa, mela=mela, unicode=unicode)) degrees = core.mela_to_degrees(mela) # Rotate degrees relative to Sa degrees = np.mod(degrees + Sa, 12) axis.set_major_locator( FixedLocator(np.add.outer(12 * np.arange(10), degrees).ravel())) axis.set_label_text("Svara") elif ax_type in ["tempo", "fourier_tempo"]: axis.set_major_formatter(ScalarFormatter()) axis.set_major_locator(LogLocator(base=2.0)) axis.set_label_text("BPM") elif ax_type == "time": axis.set_major_formatter(TimeFormatter(unit=None, lag=False)) axis.set_major_locator( MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10])) axis.set_label_text("Time") elif ax_type == "s": axis.set_major_formatter(TimeFormatter(unit="s", lag=False)) axis.set_major_locator( MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10])) axis.set_label_text("Time (s)") elif ax_type == "ms": axis.set_major_formatter(TimeFormatter(unit="ms", lag=False)) axis.set_major_locator( MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10])) axis.set_label_text("Time (ms)") elif ax_type == "lag": axis.set_major_formatter(TimeFormatter(unit=None, lag=True)) axis.set_major_locator( MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10])) axis.set_label_text("Lag") elif ax_type == "lag_s": axis.set_major_formatter(TimeFormatter(unit="s", lag=True)) axis.set_major_locator( MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10])) axis.set_label_text("Lag (s)") elif ax_type == "lag_ms": axis.set_major_formatter(TimeFormatter(unit="ms", lag=True)) axis.set_major_locator( MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10])) axis.set_label_text("Lag (ms)") elif ax_type == "cqt_note": axis.set_major_formatter(NoteFormatter(key=key, unicode=unicode)) # Where is C1 relative to 2**k hz? log_C1 = np.log2(core.note_to_hz("C1")) C_offset = 2.0**(log_C1 - np.floor(log_C1)) axis.set_major_locator(LogLocator(base=2.0, subs=(C_offset, ))) axis.set_minor_formatter( NoteFormatter(key=key, major=False, unicode=unicode)) axis.set_minor_locator( LogLocator(base=2.0, subs=C_offset * 2.0**(np.arange(1, 12) / 12.0))) axis.set_label_text("Note") elif ax_type == "cqt_svara": axis.set_major_formatter( SvaraFormatter(Sa=Sa, mela=mela, unicode=unicode)) # Find the offset of Sa relative to 2**k Hz sa_offset = 2.0**(np.log2(Sa) - np.floor(np.log2(Sa))) axis.set_major_locator(LogLocator(base=2.0, subs=(sa_offset, ))) axis.set_minor_formatter( SvaraFormatter(Sa=Sa, mela=mela, major=False, unicode=unicode)) axis.set_minor_locator( LogLocator(base=2.0, subs=sa_offset * 2.0**(np.arange(1, 12) / 12.0))) axis.set_label_text("Svara") elif ax_type in ["cqt_hz"]: axis.set_major_formatter(LogHzFormatter()) log_C1 = np.log2(core.note_to_hz("C1")) C_offset = 2.0**(log_C1 - np.floor(log_C1)) axis.set_major_locator(LogLocator(base=2.0, subs=(C_offset, ))) axis.set_major_locator(LogLocator(base=2.0)) axis.set_minor_formatter(LogHzFormatter(major=False)) axis.set_minor_locator( LogLocator(base=2.0, subs=C_offset * 2.0**(np.arange(1, 12) / 12.0))) axis.set_label_text("Hz") elif ax_type == "fft_note": axis.set_major_formatter(NoteFormatter(key=key, unicode=unicode)) # Where is C1 relative to 2**k hz? log_C1 = np.log2(core.note_to_hz("C1")) C_offset = 2.0**(log_C1 - np.floor(log_C1)) axis.set_major_locator(SymmetricalLogLocator(axis.get_transform())) axis.set_minor_formatter( NoteFormatter(key=key, major=False, unicode=unicode)) axis.set_minor_locator( LogLocator(base=2.0, subs=2.0**(np.arange(1, 12) / 12.0))) axis.set_label_text("Note") elif ax_type == "fft_svara": axis.set_major_formatter( SvaraFormatter(Sa=Sa, mela=mela, unicode=unicode)) # Find the offset of Sa relative to 2**k Hz log_Sa = np.log2(Sa) sa_offset = 2.0**(log_Sa - np.floor(log_Sa)) axis.set_major_locator( SymmetricalLogLocator(axis.get_transform(), base=2.0, subs=[sa_offset])) axis.set_minor_formatter( SvaraFormatter(Sa=Sa, mela=mela, major=False, unicode=unicode)) axis.set_minor_locator( LogLocator(base=2.0, subs=sa_offset * 2.0**(np.arange(1, 12) / 12.0))) axis.set_label_text("Svara") elif ax_type in ["mel", "log"]: axis.set_major_formatter(ScalarFormatter()) axis.set_major_locator(SymmetricalLogLocator(axis.get_transform())) axis.set_label_text("Hz") elif ax_type in ["linear", "hz", "fft"]: axis.set_major_formatter(ScalarFormatter()) axis.set_label_text("Hz") elif ax_type in ["frames"]: axis.set_label_text("Frames") elif ax_type in ["off", "none", None]: axis.set_label_text("") axis.set_ticks([]) else: raise ParameterError("Unsupported axis type: {}".format(ax_type))
def plot_obs(self, Lmax=True, Lpp=False, Kp=True, Dst=True, clims=[0, 10], title=None, values=None): """ Create a summary plot of the observations. For reference, the last closed drift shell, Dst, and Kp are all included. These can be disabled individually using the corresponding boolean kwargs. The clims kwarg can be used to manually set the color bar range. To use, set it equal to a two-element list containing minimum and maximum Log_10 value to plot. Default action is to use [0,10] as the log_10 of the color range. This is good enough for most applications. The title of the top most plot defaults to 'Summary Plot' but can be customized using the title kwarg. The figure object and all three axis objects (PSD axis, Dst axis, and Kp axis) are all returned to allow the user to further customize the plots as necessary. If any of the plots are excluded, None is returned in their stead. Examples ======== >>> rb.plot_obs(Lmax=False, Kp=False, clims=[2,10], title='Observations Plot') This command would create the summary plot with a color bar range of 100 to 10^10. The Lmax line and Kp values would be excluded. The title of the topmost plot (phase space density) would be set to 'Good work!'. """ import spacepy.data_assimilation import matplotlib.pyplot as p from matplotlib.colors import LogNorm from matplotlib.ticker import (LogLocator, LogFormatter, LogFormatterMathtext) import pdb # debugging command #pdb.set_trace() # test for default values if values is None: values = self.PSDdata # Initialize axis variables so that they can be returned, # even if not used. ax1 = None ax2 = None ax3 = None fig = p.figure() fig.subplots_adjust(left=0.10, right=0.999, top=0.92) # compute time-window average observation value y = np.array([], dtype=float) Lobs = np.array([], dtype=float) eDOYobs = np.array([], dtype=float) nTAI = len(self.ticks) # time loop for i, Tnow, Tfut in zip( np.arange(nTAI - 1) + 1, self.ticks[:-1], self.ticks[1:]): if len(values[i - 1]) > 0: # get observations for time window ]Tnow-Twindow,Tnow] Lobs_tmp, y_tmp = spacepy.data_assimilation.average_window( values[i - 1], self.Lgrid) y = np.append(y, y_tmp) Lobs = np.append(Lobs, Lobs_tmp) eDOYobs = np.append( eDOYobs, np.ones(len(y_tmp)) * self.ticks.eDOY[i - 1]) # PLOT PSDdata if Kp or Dst: ax1 = p.subplot(2, 1, 1) else: ax1 = p.subplot(1, 1, 1) # Plot phase space density observations. map = ax1.scatter(eDOYobs, Lobs, c=y, norm=LogNorm(), vmin=10.0**clims[0], vmax=10.0**clims[1], edgecolor='none') ax1.set_ylabel('L*') if title is not None: ax1.set_title(title) ax1.set_ylim(self.Lgrid[0], self.Lgrid[len(self.Lgrid) - 1]) # Add color bar. cbar = p.colorbar(map, pad=0.01, shrink=.85, ticks=LogLocator(), format=LogFormatterMathtext()) cbar.set_label('Phase Space Density') # add Lmax line if Lmax: p.plot(self.ticks.eDOY, self.params['Lmax'], 'w') # Minimize time range. ax1.set_xlim([self.ticks.eDOY[0], self.ticks.eDOY[-1]]) # Finally, save the position of the plot to make next plot match. pos = ax1.get_position() if Dst is True: ax2 = p.subplot(2, 1, 2) pos2 = ax2.get_position() pos2.x1 = pos.x1 ax2.set_position(pos2) ax2.plot(self.ticks.eDOY, self.params['Dst'], color='r') ax2.set_xlabel('DOY in ' + str(self.ticks.UTC[0].year)) ax2.set_ylabel('Dst', color='r') for tl in ax2.get_yticklabels(): tl.set_color('r') ax2.set_xlim([self.ticks.eDOY[0], self.ticks.eDOY[-1]]) if Kp is True: if Dst is True: p.subplot(2, 1, 2) ax3 = p.twinx() else: ax3 = p.subplot(2, 1, 2) pos3 = ax3.get_position() pos3.x1 = pos.x1 ax3.set_position(pos3) ax3.plot(self.ticks.eDOY, self.params['Kp'], 'k:') if Dst is True: ax3.yaxis.tick_right() ax3.set_xlabel('DOY in ' + str(self.ticks.UTC[0].year)) ax3.set_ylabel('Kp') ax3.set_xlim([self.ticks.eDOY[0], self.ticks.eDOY[-1]]) #p.show() return fig, ax1, ax2, ax3
ax[i].plot(MSDav, marker='o', markeredgecolor='black', markerfacecolor='#228a8d', linestyle='None') ax[i].set_xscale('log') ax[i].set_yscale('log') ax[i].set( ylabel= r'$\langle \overline {\Updelta \mathbf{r}^2(\Updelta t, T)}\rangle$ ($\mathrm{\upmu}$m$^2$)', xlabel=r'$T$ (s)') ax[i].set_ylim((1e-6, 1)) ax[i].yaxis.set_ticks_position('both') ax[i].xaxis.set_ticks_position('both') ax[i].tick_params(which="both", axis="both", direction="in") ax[i].xaxis.set_major_locator(LogLocator(base=10, numticks=5)) locmin = LogLocator(base=10.0, subs=tuple(np.arange(0.1, 1, 0.1)), numticks=5) ax[i].xaxis.set_minor_locator(locmin) ax[i].xaxis.set_minor_formatter(NullFormatter()) ax[i].yaxis.set_major_locator(LogLocator(base=10, numticks=7)) locmin = LogLocator(base=10.0, subs=tuple(np.arange(0.1, 1, 0.1)), numticks=7) ax[i].yaxis.set_minor_locator(locmin) ax[i].yaxis.set_minor_formatter(NullFormatter()) ax[i].text(0.9, 0.92,
def plot_data(data): signal_format = None # 'line' or 'hist' or None Total_SM_label = False # for Total SM black line in plot and legend plot_label = r'$H \rightarrow \gamma\gamma$' signal_label = '' # ******************* # general definitions (shouldn't need to change) lumi_used = str(HyyAnalysis.lumi*HyyAnalysis.fraction) signal = None for s in HyySamples.samples.keys(): if s not in HyyAnalysis.stack_order and s!='data': signal = s for x_variable,hist in HyyHistograms.hist_dict.items(): h_bin_width = hist['bin_width'] h_num_bins = hist['num_bins'] h_xrange_min = hist['xrange_min'] h_xlabel = hist['xlabel'] h_log_y = hist['log_y'] h_y_label_x_position = hist['y_label_x_position'] h_legend_loc = hist['legend_loc'] h_log_top_margin = hist['log_top_margin'] # to decrease the separation between data and the top of the figure, remove a 0 h_linear_top_margin = hist['linear_top_margin'] # to decrease the separation between data and the top of the figure, pick a number closer to 1 bins = [h_xrange_min + x*h_bin_width for x in range(h_num_bins+1) ] bin_centres = [h_xrange_min+h_bin_width/2 + x*h_bin_width for x in range(h_num_bins) ] data_x,_ = np.histogram(data['data'][x_variable].values, bins=bins) data_x_errors = np.sqrt(data_x) # data fit polynomial_mod = PolynomialModel(4) gaussian_mod = GaussianModel() bin_centres_array = np.asarray(bin_centres) pars = polynomial_mod.guess(data_x, x=bin_centres_array, c0=data_x.max(), c1=0, c2=0, c3=0, c4=0) pars += gaussian_mod.guess(data_x, x=bin_centres_array, amplitude=91.7, center=125., sigma=2.4) model = polynomial_mod + gaussian_mod out = model.fit(data_x, pars, x=bin_centres_array, weights=1/data_x_errors) # background part of fit params_dict = out.params.valuesdict() c0 = params_dict['c0'] c1 = params_dict['c1'] c2 = params_dict['c2'] c3 = params_dict['c3'] c4 = params_dict['c4'] background = c0 + c1*bin_centres_array + c2*bin_centres_array**2 + c3*bin_centres_array**3 + c4*bin_centres_array**4 signal_x = None if signal_format=='line': signal_x,_ = np.histogram(data[signal][x_variable].values,bins=bins,weights=data[signal].totalWeight.values) elif signal_format=='hist': signal_x = data[signal][x_variable].values signal_weights = data[signal].totalWeight.values signal_color = HyySamples.samples[signal]['color'] signal_x = data_x - background mc_x = [] mc_weights = [] mc_colors = [] mc_labels = [] mc_x_tot = np.zeros(len(bin_centres)) for s in HyyAnalysis.stack_order: mc_labels.append(s) mc_x.append(data[s][x_variable].values) mc_colors.append(HyySamples.samples[s]['color']) mc_weights.append(data[s].totalWeight.values) mc_x_heights,_ = np.histogram(data[s][x_variable].values,bins=bins,weights=data[s].totalWeight.values) mc_x_tot = np.add(mc_x_tot, mc_x_heights) mc_x_err = np.sqrt(mc_x_tot) # ************* # Main plot # ************* plt.axes([0.1,0.3,0.85,0.65]) #(left, bottom, width, height) main_axes = plt.gca() main_axes.errorbar( x=bin_centres, y=data_x, yerr=data_x_errors, fmt='ko', label='Data') if Total_SM_label: totalSM_handle, = main_axes.step(bins,np.insert(mc_x_tot,0,mc_x_tot[0]),color='black') if signal_format=='line': main_axes.step(bins,np.insert(signal_x,0,signal_x[0]),color=HyySamples.samples[signal]['color'], linestyle='--', label=signal) elif signal_format=='hist': main_axes.hist(signal_x,bins=bins,bottom=mc_x_tot,weights=signal_weights,color=signal_color,label=signal) main_axes.bar(bin_centres,2*mc_x_err,bottom=mc_x_tot-mc_x_err,alpha=0.5,color='none',hatch="////", width=h_bin_width, label='Stat. Unc.') main_axes.plot(bin_centres, out.best_fit, '-r', label='Sig+Bkg Fit ($m_H=125$ GeV)') main_axes.plot(bin_centres, background, '--r', label='Bkg (4th order polynomial)') main_axes.set_xlim(left=h_xrange_min,right=bins[-1]) main_axes.xaxis.set_minor_locator(AutoMinorLocator()) # separation of x axis minor ticks main_axes.tick_params(which='both',direction='in',top=True,labeltop=False,labelbottom=False,right=True,labelright=False) if len(h_xlabel.split('['))>1: y_units = ' '+h_xlabel[h_xlabel.find("[")+1:h_xlabel.find("]")] else: y_units = '' main_axes.set_ylabel(r'Events / '+str(h_bin_width)+y_units,fontname='sans-serif',horizontalalignment='right',y=1.0,fontsize=11) if h_log_y: main_axes.set_yscale('log') smallest_contribution = mc_heights[0][0] smallest_contribution.sort() bottom = smallest_contribution[-2] top = np.amax(data_x)*h_log_top_margin main_axes.set_ylim(bottom=bottom,top=top) main_axes.yaxis.set_major_formatter(CustomTicker()) locmin = LogLocator(base=10.0,subs=(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),numticks=12) main_axes.yaxis.set_minor_locator(locmin) else: main_axes.set_ylim(bottom=0,top=(np.amax(data_x)+math.sqrt(np.amax(data_x)))*h_linear_top_margin) main_axes.yaxis.set_minor_locator(AutoMinorLocator()) main_axes.yaxis.get_major_ticks()[0].set_visible(False) plt.text(0.2,0.97,'ATLAS Open Data',ha="left",va="top",family='sans-serif',transform=main_axes.transAxes,fontsize=13) plt.text(0.2,0.9,'for education',ha="left",va="top",family='sans-serif',transform=main_axes.transAxes,style='italic',fontsize=8) plt.text(0.2,0.86,r'$\sqrt{s}=13\,\mathrm{TeV},\;\int L\,dt=$'+lumi_used+'$\,\mathrm{fb}^{-1}$',ha="left",va="top",family='sans-serif',transform=main_axes.transAxes) plt.text(0.2,0.78,plot_label,ha="left",va="top",family='sans-serif',transform=main_axes.transAxes) # Create new legend handles but use the colors from the existing ones handles, labels = main_axes.get_legend_handles_labels() if signal_format=='line': handles[labels.index(signal)] = Line2D([], [], c=HyySamples.samples[signal]['color'], linestyle='dashed') if Total_SM_label: uncertainty_handle = mpatches.Patch(facecolor='none',hatch='////') handles.append((totalSM_handle,uncertainty_handle)) labels.append('Total SM') # specify order within legend new_handles = [handles[labels.index('Data')]] new_labels = ['Data'] for s in reversed(HyyAnalysis.stack_order): new_handles.append(handles[labels.index(s)]) new_labels.append(s) if Total_SM_label: new_handles.append(handles[labels.index('Total SM')]) new_labels.append('Total SM') else: new_handles.append(handles[labels.index('Sig+Bkg Fit ($m_H=125$ GeV)')]) new_handles.append(handles[labels.index('Bkg (4th order polynomial)')]) new_labels.append('Sig+Bkg Fit ($m_H=125$ GeV)') new_labels.append('Bkg (4th order polynomial)') if signal is not None: new_handles.append(handles[labels.index(signal)]) new_labels.append(signal_label) main_axes.legend(handles=new_handles, labels=new_labels, frameon=False, loc=h_legend_loc) # ************* # Data-Bkg plot # ************* plt.axes([0.1,0.1,0.85,0.2]) #(left, bottom, width, height) ratio_axes = plt.gca() ratio_axes.yaxis.set_major_locator(MaxNLocator(nbins='auto',symmetric=True)) ratio_axes.errorbar( x=bin_centres, y=signal_x, yerr=data_x_errors, fmt='ko') ratio_axes.plot(bin_centres, out.best_fit-background, '-r') ratio_axes.plot(bin_centres, background-background, '--r') ratio_axes.set_xlim(left=h_xrange_min,right=bins[-1]) ratio_axes.xaxis.set_minor_locator(AutoMinorLocator()) # separation of x axis minor ticks ratio_axes.xaxis.set_label_coords(0.9,-0.2) # (x,y) of x axis label # 0.2 down from x axis ratio_axes.set_xlabel(h_xlabel,fontname='sans-serif',fontsize=11) ratio_axes.tick_params(which='both',direction='in',top=True,labeltop=False,right=True,labelright=False) ratio_axes.yaxis.set_minor_locator(AutoMinorLocator()) if signal_format=='line' or signal_format=='hist': ratio_axes.set_ylabel(r'Data/SM',fontname='sans-serif',x=1,fontsize=11) else: ratio_axes.set_ylabel(r'Events-Bkg',fontname='sans-serif',x=1,fontsize=11) # Generic features for both plots main_axes.yaxis.set_label_coords(h_y_label_x_position,1) ratio_axes.yaxis.set_label_coords(h_y_label_x_position,0.5) plt.savefig("Hyy_"+x_variable+".pdf",bbox_inches='tight') print('chi^2 = '+str(out.chisqr)) print('gaussian centre = '+str(params_dict['center'])) print('gaussian sigma = '+str(params_dict['sigma'])) print('gaussian fwhm = '+str(params_dict['fwhm'])) return signal_x,mc_x_tot
def show_noise_plot(self, cfig): cdiag = self.diag cparams = cdiag['params'] vox_size = cparams['voxel_size'] name = cparams['name'] maxfreq = cparams['max_frequency'] N = self.M.shape[0] rad_cutoff = cparams.get('rad_cutoff', 1.0) rad = min(rad_cutoff, maxfreq * 2.0 * vox_size) startI = int((1 - rad) * N / 2) + 1 endI = N / 2 + int(rad * N / 2) + 1 imextent = [ startI - (N + 1.0) / 2, endI - (N + 1.0) / 2, startI - (N + 1.0) / 2, endI - (N + 1.0) / 2 ] imextent = [e / (2.0 * vox_size) / (N / 2) for e in imextent] sigma_est = cparams['sigma'] sigma_mle = np.sqrt(cdiag['sigma2_mle']) train_sigma_est = np.sqrt(cdiag['train_sigma2_est']).reshape((N, N)) test_sigma_est = np.sqrt(cdiag['test_sigma2_est']).reshape((N, N)) showsigma = isinstance(sigma_est, np.ndarray) vmin = min( [np.min(sigma_est), sigma_mle[startI:endI, startI:endI].min()]) vmax = max( [np.max(sigma_est), sigma_mle[startI:endI, startI:endI].max()]) imshow_kws = { 'interpolation':'nearest', \ 'vmin':vmin, 'vmax':vmax, 'extent':imextent, \ 'norm':LogNorm(vmin=vmin, vmax=vmax) } cbaxs = [] plt.figure(cfig.number) plt.clf() plt.subplot(2, 1, 1) raps = np.sqrt(cryoem.rotational_average(train_sigma_est**2)) fs = np.linspace(0, (len(raps) - 1) / (N / 2.0) / (2.0 * vox_size), len(raps)) plt.plot(fs, raps, label='Training RMSE') raps = np.sqrt(cryoem.rotational_average(test_sigma_est**2)) fs = np.linspace(0, (len(raps) - 1) / (N / 2.0) / (2.0 * vox_size), len(raps)) plt.plot(fs, raps, label='Testing RMSE') plt.legend() plt.grid() if showsigma: cbaxs.append(plt.subplot(2, 2, 3)) else: cbaxs.append(plt.subplot(2, 1, 2)) im = plt.imshow(sigma_mle[startI:endI, startI:endI], **imshow_kws) plt.title('Freq RMSE (MLE)') if showsigma: sigma_est = sigma_est.reshape((N, N)) cbaxs.append(plt.subplot(2, 2, 4)) im = plt.imshow(sigma_est[startI:endI, startI:endI], **imshow_kws) plt.title('Coloured Noise Std Dev') plt.subplot(2, 1, 1) if showsigma: raps = np.sqrt(cryoem.rotational_average(sigma_est**2)) fs = np.linspace(0, (len(raps) - 1) / (N / 2.0) / (2.0 * vox_size), len(raps)) else: raps = [sigma_est, sigma_est] fs = [fs[0], fs[-1]] plt.plot(fs, raps, label='Noise Std Dev') plt.xlim((0, rad / (2.0 * vox_size))) plt.yscale('log', basey=2) plt.legend() plt.title(name + ' Noise Levels') plt.colorbar(im, ax=cbaxs, ticks=LogLocator(base=2), format=LogFormatterMathtext(base=2))
def make_scatter_data(patient): """Create scatter plot for the given patient. :param patient: patient directory containing plot_dict.txt :type patient: str """ patient_scores_dir = patient plot_dict_file = os.path.join(patient_scores_dir, 'plot_dict.txt') if os.path.exists(patient_scores_dir): try: temp_plot_dict = json.load(open(plot_dict_file)) if os.path.exists( plot_dict_file) else None except: temp_plot_dict = None else: temp_plot_dict = None #plot_dict = make_scatter_plot_dict(scores_dict[patient]) plot_dict = scores_dict[patient] if not temp_plot_dict or (plot_dict != temp_plot_dict): emotions = AUScorer.emotion_list() emotions.append('Neutral') temp_data = {emotion: [] for emotion in emotions} for vid in sorted(plot_dict.keys()): for frame in sorted(plot_dict[vid].keys()): for emotion in emotions: if emotion in plot_dict[vid][frame][0]: temp_data[emotion].append(plot_dict[vid][frame][1]) else: temp_data[emotion].append(0) # for index, emotion in enumerate(emotions): # new_row = [] # for vid in sorted(plot_dict[emotion].keys()): # for frame in sorted(plot_dict[emotion][vid].keys()): # new_row.append(plot_dict[emotion][vid][frame]) # z = (list(new_row)) # temp_data[emotion] = z data = [] for index, emotion in enumerate( sorted(x for x in emotions if x != 'Neutral')): data.append([ x + 0.00000000000000000000000000000001 for x in temp_data[emotion] ]) neutral_data = [ 0.00000000000000000000000000000001 for _ in range(len(data[0])) ] emotion_dict = { 'Angry': .4, 'Sad': .3, 'Happy': .3, 'Disgust': .3, 'Fear': .5, 'Surprise': .5 } for index, datum in enumerate(data): emotion = emotions[index] for index, val in enumerate(datum): if val < emotion_dict[emotion]: datum[index] = 0.00000000000000000000000000000001 neutral_data[index] = max(val, neutral_data[index]) data.append(neutral_data) # real_data = np.ndarray((len(temp_data),)) # for index, vals in enumerate(data): # real_data[index] = vals if all(data): # contains = False data = np.asarray(data, dtype=np.float64) # for _ in data: # for index, val in enumerate(_): # if val < 1.5: # _[index] = 0 # else: # contains = True # if contains: if not os.path.exists(patient): os.mkdir(patient) # cict = { # 'red': ((0.0, 0.0, 0.0), # (1.0, 0.0, 0.0)), # # 'green': ((0.0, 0.0, 0.0), # (1.0, 0.0, 0.0)), # # 'blue': ((0.0, 0.0, 0.0), # (.25, 0.0, 1.0), # (1.0, 1.0, 1.0)) # } # test_colormap = matplotlib.colors.ListedColormap('test', cict) ax = sns.heatmap( data, cbar_kws={'ticks': LogLocator()}, yticklabels=emotions, xticklabels=False, cmap='BuGn', norm=matplotlib.colors.LogNorm()) # ax.set_clim(vmin=1.5, vmax=5) ax.set_title(patient) fig = ax.get_figure() fig.savefig(os.path.join(patient, 'day_scores.png')) # print(patient) plt.close() json.dump(plot_dict, open(plot_dict_file, 'w'))
def plot_objective( result, levels=10, n_points=40, n_samples=250, size=2, zscale="linear", dimensions=None, n_random_restarts=100, alpha=0.5, colors=None, fig=None, ax=None, ): """Pairwise partial dependence plot of the objective function. The diagonal shows the partial dependence for dimension `i` with respect to the objective function. The off-diagonal shows the partial dependence for dimensions `i` and `j` with respect to the objective function. The objective function is approximated by `result.model.` Pairwise scatter plots of the points at which the objective function was directly evaluated are shown on the off-diagonal. A red point indicates the found minimum. Note: search spaces that contain `Categorical` dimensions are currently not supported by this function. Parameters ---------- * `result` [`OptimizeResult`] The result for which to create the scatter plot matrix. * `levels` [int, default=10] Number of levels to draw on the contour plot, passed directly to `plt.contour()`. * `n_points` [int, default=40] Number of points at which to evaluate the partial dependence along each dimension. * `n_samples` [int, default=250] Number of random samples to use for averaging the model function at each of the `n_points`. * `size` [float, default=2] Height (in inches) of each facet. * `zscale` [str, default='linear'] Scale to use for the z axis of the contour plots. Either 'linear' or 'log'. * `dimensions` [list of str, default=None] Labels of the dimension variables. `None` defaults to `space.dimensions[i].name`, or if also `None` to `['X_0', 'X_1', ..]`. * `n_random_restarts` [int, default=100] Number of restarts to try to find the global optimum. * `alpha` [float, default=0.5] Transparency of the sampled points. * `colors` [list of tuples, default=None] Colors to use for the optima. * `fig` [Matplotlib figure, default=None] Figure to use for plotting. If None, it will create one. * `ax` [k x k axes, default=None] Axes on which to plot the marginals. If None, it will create appropriate axes. Returns ------- * `ax`: [`Axes`]: The matplotlib axes. """ if colors is None: colors = plt.cm.get_cmap("Set3").colors space = result.space samples = np.asarray(result.x_iters) rvs_transformed = space.transform(space.rvs(n_samples=n_samples)) if zscale == "log": locator = LogLocator() elif zscale == "linear": locator = None else: raise ValueError("Valid values for zscale are 'linear' and 'log'," " not '%s'." % zscale) if fig is None: fig, ax = plt.subplots( space.n_dims, space.n_dims, figsize=(size * space.n_dims, size * space.n_dims), ) fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, hspace=0.1, wspace=0.1) failures = 0 while True: try: with result.models[-1].noise_set_to_zero(): min_x = expected_ucb(result, alpha=0.0, n_random_starts=n_random_restarts)[0] min_ucb = expected_ucb(result, n_random_starts=n_random_restarts)[0] except: failures += 1 if failures == 10: break continue else: break for i in range(space.n_dims): for j in range(space.n_dims): if i == j: xi, yi = partial_dependence( space, result.models[-1], i, j=None, sample_points=rvs_transformed, n_points=n_points, ) yi_min, yi_max = np.min(yi), np.max(yi) ax[i, i].plot(xi, yi, color=colors[1]) if failures != 10: ax[i, i].axvline(min_x[i], linestyle="--", color=colors[3], lw=1) ax[i, i].axvline(min_ucb[i], linestyle="--", color=colors[5], lw=1) ax[i, i].text( min_x[i], yi_min + 0.9 * (yi_max - yi_min), f"{np.around(min_x[i], 4)}", color=colors[3], ) ax[i, i].text( min_ucb[i], yi_min + 0.7 * (yi_max - yi_min), f"{np.around(min_ucb[i], 4)}", color=colors[5], ) # lower triangle elif i > j: xi, yi, zi = partial_dependence(space, result.models[-1], i, j, rvs_transformed, n_points) ax[i, j].contourf(xi, yi, zi, levels, locator=locator, cmap="viridis_r") ax[i, j].scatter(samples[:, j], samples[:, i], c="k", s=10, lw=0.0, alpha=alpha) if failures != 10: ax[i, j].scatter(min_x[j], min_x[i], c=["r"], s=20, lw=0.0) ax[i, j].scatter(min_ucb[j], min_ucb[i], c=["xkcd:orange"], s=20, lw=0.0) return _format_scatter_plot_axes(ax, space, ylabel="Partial dependence", dim_labels=dimensions)
for i in range(1, len(dts)): d = dts[i] label = d plt.plot(data["Ef"], data[d], label=label) plt.xscale("log") v = list(plt.axis()) v[0] = data["Ef"][0] v[1] = data["Ef"][-1] v[2] = 0 v[3] = 0.08 plt.axis(v) plt.gca().xaxis.set_minor_locator(LogLocator(subs="all", numticks=1e5)) plt.gca().set_yticks(np.arange(v[2], v[3] + 1e-5, 0.005), minor=True) plt.xlabel(r"$E_f{\rm\ [GeV]}$") plt.ylabel(r"$\bar P_{%s %s}^{\rm vis}$" % (flavor_texs[a], flavor_texs[b])) s = r"${\rm Visible}$" s += "\n" if m1 == 0: s += r"$m_1=0$" else: s += r"$m_1=%g{\rm\ eV}$" % m1 s += "$,$ " s += r"$z=%g$" % z s += "\n" s += r"$\gamma=%g$" % gamma
def plot(self, Lmax=True, Lpp=False, Kp=True, Dst=True, clims=[0, 10], title=None, values=None): """ Create a summary plot of the RadBelt object distribution function. For reference, the last closed drift shell, Dst, and Kp are all included. These can be disabled individually using the corresponding Boolean kwargs. The clims kwarg can be used to manually set the color bar range. To use, set it equal to a two-element list containing minimum and maximum Log_10 value to plot. Default action is to use [0,10] as the log_10 of the color range. This is good enough for most applications. The title of the top most plot defaults to 'Summary Plot' but can be customized using the title kwarg. The figure object and all three axis objects (PSD axis, Dst axis, and Kp axis) are all returned to allow the user to further customize the plots as necessary. If any of the plots are excluded, None is returned in their stead. Examples ======== >>> rb.plot(Lmax=False, Kp=False, clims=[2,10], title='Good work!') This command would create the summary plot with a color bar range of 100 to 10^10. The Lmax line and Kp values would be excluded. The title of the topmost plot (phase space density) would be set to 'Good work!'. """ import matplotlib.pyplot as p from matplotlib.colors import LogNorm from matplotlib.ticker import (LogLocator, LogFormatter, LogFormatterMathtext) import pdb # debugging command #pdb.set_trace() # test for default values if values is None: values = self.PSD # Initialize axis variables so that they can be returned, # even if not used. ax1 = None ax2 = None ax3 = None fig = p.figure() fig.subplots_adjust(left=0.10, right=0.999, top=0.92) # PLOT PSD if Kp or Dst: ax1 = p.subplot(2, 1, 1) else: ax1 = p.subplot(1, 1, 1) # Plot phase space density, masking out values of 0. map = ax1.pcolorfast(self.ticks.eDOY, self.Lgrid, np.where(values > 0.0, self.PSD, 10.0**-39), vmin=10.0**clims[0], vmax=10.0**clims[1], norm=LogNorm()) ax1.set_ylabel('L*') if title is not None: ax1.set_title(title) # Add color bar. cbar = p.colorbar(map, pad=0.01, shrink=.85, ticks=LogLocator(), format=LogFormatterMathtext()) cbar.set_label('Phase Space Density') # add Lmax line if Lmax: p.plot(self.ticks.eDOY, self.params['Lmax'], 'w') # Minimize time range. ax1.set_xlim([self.ticks.eDOY[0], self.ticks.eDOY[-1]]) # Finally, save the position of the plot to make next plot match. pos = ax1.get_position() if Dst is True: ax2 = p.subplot(2, 1, 2) pos2 = ax2.get_position() pos2.x1 = pos.x1 ax2.set_position(pos2) ax2.plot(self.ticks.eDOY, self.params['Dst'], color='r') ax2.set_xlabel('DOY in ' + str(self.ticks.UTC[0].year)) ax2.set_ylabel('Dst', color='r') for tl in ax2.get_yticklabels(): tl.set_color('r') ax2.set_xlim([self.ticks.eDOY[0], self.ticks.eDOY[-1]]) if Kp is True: if Dst is True: p.subplot(2, 1, 2) ax3 = p.twinx() else: ax3 = p.subplot(2, 1, 2) pos3 = ax3.get_position() pos3.x1 = pos.x1 ax3.set_position(pos3) ax3.plot(self.ticks.eDOY, self.params['Kp'], 'k:') if Dst is True: ax3.yaxis.tick_right() ax3.set_xlabel('DOY in ' + str(self.ticks.UTC[0].year)) ax3.set_ylabel('Kp') ax3.set_xlim([self.ticks.eDOY[0], self.ticks.eDOY[-1]]) #p.show() return fig, ax1, ax2, ax3
def __drawData(self, fig): ax = fig.add_axes([0.1, 0.2, 0.85, 0.7]) x, y = self.__extractPlotTables() # truncate along x-axis if desired if self.xlimit is not None: x = x[:self.xlimit / self.binSize] y = y[:self.xlimit / self.binSize] # compute linear fit and r2 if not self.linearY: ylog = np.log10(y) xcof = np.vstack((x, np.ones(len(x)))).T temp = 900 / self.binSize model, resid = np.linalg.lstsq(xcof[:temp], ylog[:temp])[:2] r2 = 1 - resid / (ylog.size * ylog.var()) plotlist = [] legend = [] plotlist.append( plt.plot(x, y, color=self.colorList[1], linestyle='none', marker='.', markeredgecolor=self.colorList[1], markeredgewidth=0, linewidth=0.5, markersize=6.0, alpha=0.75)[0]) legend += ['Data'] if self.bgRate is not None: plotlist.append( plt.plot(x, self.__rateFn(x), color=self.colorList[6], linestyle='solid', marker='None', markeredgecolor=self.colorList[6], markeredgewidth=0, linewidth=2.5, markersize=6.0, alpha=0.9)[0]) legend += ['Background'] if not self.linearY: temp = x[:100000 / self.binSize] plotlist.append( plt.plot(temp, np.power(10, model[0] * temp + model[1]), color=self.colorList[2], linestyle='solid', marker='None', markeredgecolor=self.colorList[2], markeredgewidth=0, linewidth=2.5, markersize=10.0, alpha=0.9)[0]) legend += ['Linear Fit r2=%s' % r2] xmin, xmax = plt.xlim() ymin, ymax = plt.ylim() if xmin < -1.0: plt.xlim(0 - .02 * xmax, xmax * 1.02) else: plt.xlim(xmax - ((xmax - xmin) * 1.02), xmax * 1.02) pltTitle = plt.title(self.title) plt.setp(pltTitle, fontsize='x-small') # legend fontsize for loc, spine in ax.spines.iteritems(): if loc in ['left', 'bottom']: # outward by 10 points spine.set_position(('outward', 10)) elif loc in ['right', 'top']: # don't draw spine spine.set_color('none') else: raise ValueError('unknown spine location: %s' % loc) # turn off ticks where there is no spine ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') if not self.linearY: ax.set_yscale('log') ax.yaxis.set_minor_locator(LogLocator(base=10, subs=range(1, 10))) ax.yaxis.set_data_interval(0.01, None) plt.xlabel('Distance') plt.ylabel('Count') plt.ylim(ymin=0.5) leg = plt.legend(plotlist, legend, loc=1, numpoints=1) plt.setp(leg.get_texts(), fontsize='x-small') # legend fontsize leg._drawFrame = False
def setup(ax, indx, num_cc, count=[0]): count[0] += 1 #keep local information. data_bprm = [[], []] data_f_nm = [[], []] data_f_m = [[], []] for line in open(indx + '_bprm'): lin_1, lin_2 = [float(i) for i in line.split()] data_bprm[0].append(lin_1) data_bprm[1].append(lin_2) for line in open(indx + '_fac_no_mixing'): lin_1, lin_2 = [float(i) for i in line.split()] data_f_nm[0].append(lin_1) data_f_nm[1].append(lin_2) for line in open(indx + '_fac_mixing'): lin_1, lin_2 = [float(i) for i in line.split()] data_f_m[0].append(lin_1) data_f_m[1].append(lin_2) #ax.yaxis.set_major_locator(plt.MaxNLocator(5)) #does not work well in log scale #use LogLocator(base=10, numticks=7 as below) ax.semilogy(data_bprm[0], data_bprm[1], color='k', label=str(num_cc) + 'CC BPRM') ax.semilogy(data_f_nm[0], data_f_nm[1], '-xb', markersize=3, label='RDW (same-n CI)') ax.semilogy(data_f_m[0], data_f_m[1], '-xr', markersize=3, label='RDW (different-n CI)') ax.legend(prop={'size': 8}) #ax.yaxis.set_major_locator(LogLocator(base = 10, numticks = 2)) ax.set_yticklabels(ax.get_yticks()) labels = [ str(int(log10(float(label.get_text())))) for label in ax.get_yticklabels() ] ax.set_yticklabels(labels) ax.yaxis.set_minor_locator( LogLocator(base=10, subs=(0.2, 0.4, 0.6, 0.8), numticks=20)) ax.xaxis.set_minor_locator(AutoMinorLocator(5)) ax.set_xticks(range(0, 121, 20)) ax.set_xticklabels([]) ax.set_xlim(0, 120) ax.yaxis.set_major_locator(LogLocator(base=10, numticks=6)) #very helpful!!! ax.set_yticklabels(ax.get_yticks()) labels = [ str(int(log10(float(label.get_text())))) for label in ax.get_yticklabels() ] ax.set_yticklabels(labels) ax.yaxis.set_minor_locator( LogLocator(base=10, subs=(0.2, 0, 4, 0.6, 0.8), numticks=24)) ax.yaxis.set_minor_formatter(NullFormatter()) #does not matter ax.xaxis.set_minor_locator(AutoMinorLocator(5))
def make_plot(xval, yval, plot_type='d', y_axis_type='normal', \ legend_label=None, name=None, plot_title=None, ylabel=None, \ xlabel=None, xticks=None, yticks=None, figure_size=(16,10), \ freq_cutoff=None, publish=False): """ Takes input from sparam_data and plots calculated permittivity. Can handle multiple data sets. Plots uncertainty countour if plotting single dataset with uncertainty present and plots error bars every 25 points when plotting multiple datasets. Arguments --------- xval : array or list x-axis data. Multiple data sets must be in a list. yval : array or list y-axis data. Multiple data sets must be in a list. plot_type : str Flag for default plot types. Can be set to 'd' for the real part of epsilon, 'lf' for the imaginary part of epsilon, 'lt' for dielectric loss tangent, 'ur' for the real part of mu, 'ui' for the imaginary part of mu, or 'c' for Custom. If 'c' is used, xticks and yticks must be provided. y_axis_type : str, optional Flag for type of axis to use for the y-axis. Can be either 'normal' (default) or 'log' for a log axis. If set to log, y tick postions must be manually provided to yticks. legend_label : list of str, optional Plot legend label. Each dataset much have it's own label. Stings must be in a list. name : str, optional Required when publish=True. Used in file name of saved figure. plot_title : str, optional For use when plot_type='c'. Title of the plot. ylabel : str, optional For use when plot_type='c'. Y-axis label. xlabel : str, optional For use when plot_type='c'. X-axis label. xticks : list, optional Manually set x-axis tick locations. Required when plot_type='c'. yticks : list, optional Manually set y-axis tick locations. Required when plot_type='c' and when y_axis_type='log'. figure_size : tuple or int, optional Set the matplotlib figsize. Default: (16,10). freq_cutoff : float, optional Data points lower than freq_cutoff will not be plotted. publish : bool, optional If True save figure as .eps file. Default: False. """ # Default settings for plotting permittivity data if plot_type == 'd': # Real part plot_title = 'Real Part of the Permittivity' ylabel = r'$\epsilon^{\prime}_{r}$' xlabel = 'Frequency' rnd = 1 # decimals to round to for axes determination elif plot_type == 'lf': # Imaginary part plot_title = 'Imaginary Part of the Permittivity' ylabel = r'$\epsilon^{\prime\prime}_{r}$' xlabel = 'Frequency' rnd = 2 elif plot_type == 'lt': # Loss tan plot_title = 'Loss Tangent' ylabel = r'$tan\delta$' xlabel = 'Frequency' rnd = 2 elif plot_type == 'ur': # Real part of mu plot_title = 'Real Part of the Permeability' ylabel = r'$\mu^{\prime}_{r}$' xlabel = 'Frequency' rnd = 2 elif plot_type == 'ui': # Imaginary part of mu plot_title = 'Imaginary Part of the Permeability' ylabel = r'$\mu^{\prime\prime}_{r}$' xlabel = 'Frequency' rnd = 2 elif plot_type == 'c': # Custom plot pass else: raise Exception('Invalid plot type') # Checks if input data is in a list and determines number of things to plot # NOTE: Multiple data sets must be in a list if isinstance(xval, list): number_to_compare = len(xval) else: number_to_compare = 1 xval = [xval] yval = [yval] # If no label is specified, make one if not legend_label: # If legend_label is None legend_label = [] # Label for first dataset is 'Data 1', next is 'Data 2', etc... for n in range(0, len(xval)): legend_label.append('Data {}'.format(n + 1)) else: # If legend_label is a list, make sure no list items are None for n in range(0, len(xval)): # If a list item is None, make it a label if not legend_label[n]: legend_label[n] = 'Data {}'.format(n + 1) # Remove all points lower than freq_cutoff x = [] y = [] for n in range(0, number_to_compare): if freq_cutoff: x.append(xval[n][xval[n] > freq_cutoff]) y.append(yval[n][xval[n] > freq_cutoff]) else: x.append(xval[n]) y.append(yval[n]) # Determine axes limits if plot_type != 'c': # skip for custom plots x_max = -np.inf x_min = np.inf y_max = -np.inf y_min = np.inf for n in range(0, number_to_compare): x_chk = unp.nominal_values(x[n]) max_tmp = round(max(x_chk[~np.isnan(x_chk)]), rnd) min_tmp = round(min(x_chk[~np.isnan(x_chk)])) if max_tmp > x_max: x_max = max_tmp if min_tmp < x_min: x_min = min_tmp y_chk = unp.nominal_values(y[n]) max_tmp = round(max(y_chk[~np.isnan(y_chk)]), rnd) min_tmp = round(min(y_chk[~np.isnan(y_chk)]), rnd) if max_tmp > y_max: y_max = max_tmp if min_tmp < y_min: y_min = min_tmp # Determine appropriate buffer and spacing depedning on plot type if not yticks: # skip if y ticks are manually provided thickness = y_max - y_min if plot_type in ('d', 'ur', 'ui'): if thickness < 0.1: buffer = 0.1 spacing = 0.02 else: buffer = 0.2 spacing = round((thickness + 2 * buffer) / 9, 1) elif plot_type in ('lf', 'lt', 'c'): if thickness < 0.01: buffer = 0.01 spacing = 0.002 else: buffer = 0.02 spacing = round((thickness + 2 * buffer) / 9, 2) # Makes sure the lowest point is 0 if y_min is 0 if y_min == 0: y_min += buffer elif y_min - buffer < 0: # Make sure buffer does not make ymin negative y_min = buffer # Plot f = plt.figure(figsize=figure_size) ax = f.add_subplot(111) # Plot labels ax.set_title(plot_title, fontsize=40) ax.set_ylabel(ylabel, fontsize=40) ax.set_xlabel(xlabel, fontsize=40) # Colours if number_to_compare > 6: # cycle through cubehelix palette if plotting more than 6 things ax.set_prop_cycle(cycler('color',\ sns.cubehelix_palette(number_to_compare))) else: # otherise use Dark2 palette (should be colour blind safe) ax.set_prop_cycle(cycler('color',\ sns.color_palette("Dark2",number_to_compare))) # Plot axes ax.set_xscale('log') # Set y ticks if y_axis_type == 'log': # check if y axis should be log ax.set_yscale('log') ax.set_ylim(min(yticks), max(yticks)) majorLocator_y = FixedLocator(yticks) majorFormatter_y = LogFormatter() minorLocator_y = LogLocator( subs='all' ) # Use all interger multiples of the log base for minor ticks minorFormatter_y = NullFormatter() # No minor tick labels # Apply y ticks ax.get_yaxis().set_major_locator(majorLocator_y) ax.get_yaxis().set_major_formatter(majorFormatter_y) ax.get_yaxis().set_minor_locator(minorLocator_y) ax.get_yaxis().set_minor_formatter(minorFormatter_y) elif yticks and y_axis_type == 'normal': ax.set_ylim(min(yticks), max(yticks)) ax.set_yticks(yticks) elif not yticks: # auto set ax.set_ylim(y_min - buffer, y_max + buffer) ax.set_yticks(np.arange(y_min - buffer, y_max + buffer, spacing)) # Set x ticks if xticks: x_ticklocs = xticks elif not xticks: # auto set if x_min == 0: # log of min and max x values x_logmin = 0 # don't take log of 0 else: x_logmin = np.log10(x_min) if x_max == 0: x_logmax = 0 else: x_logmax = np.log10(x_max) x_logticks = np.logspace(x_logmin, x_logmax, num=4) # 4 equaly spaced points in log space x_ticklocs = [] for n in range( len(x_logticks)): # round scientific values and make a list x_ticklocs.append(np.float(np.format_float_scientific(x_logticks[n],\ precision=0))) if len(set( x_ticklocs)) < 4: # check that this produced 4 unique values x_ticklocs = [] # if not do it again with precision = 1 for n in range(len(x_logticks)): x_ticklocs.append(np.float(np.format_float_scientific(x_logticks[n]\ ,precision=1))) majorLocator_x = FixedLocator(x_ticklocs) majorFormatter_x = EngFormatter(unit='Hz') # Format major ticks with units minorLocator_x = LogLocator( subs='all' ) # Use all interger multiples of the log base for minor ticks minorFormatter_x = NullFormatter() # No minor tick labels # Apply x ticks ax.get_xaxis().set_major_locator(majorLocator_x) ax.get_xaxis().set_major_formatter(majorFormatter_x) ax.get_xaxis().set_minor_locator(minorLocator_x) ax.get_xaxis().set_minor_formatter(minorFormatter_x) # Format the actual tick marks ax.tick_params(which='both', width=1, labelsize=30) ax.tick_params(which='major', length=7) ax.tick_params(which='minor', length=4) # Use smaller line width for minor tick grid lines ax.grid(b=True, which='major', color='w', linewidth=1.0) ax.grid(b=True, which='minor', color='w', linewidth=0.5) # Do the actual plotting if number_to_compare == 1: # plot uncertainty only if plotting one dataset ax.plot(unp.nominal_values(x[0]), unp.nominal_values(y[0]), lw=2, \ label=legend_label[0]) ax.fill_between(unp.nominal_values(x[0]), unp.nominal_values(y[0]) - \ unp.std_devs(y[0]), unp.nominal_values(y[0]) + \ unp.std_devs(y[0]), color="#3F5D7D",label='Uncertainty') else: for n in range(0, number_to_compare): ax.errorbar(unp.nominal_values(x[n]), unp.nominal_values(y[n]), \ yerr=unp.std_devs(y[n]), errorevery=25, elinewidth=1, \ capthick=1, capsize=2,lw=2,label=legend_label[n]) ax.legend(fontsize=30, loc='best') if publish: # Make file name #If save_path_for_plots already exits, use it, otherwise promt for path if 'save_path_for_plots' in globals(): datapath = save_path_for_plots else: datapath = _dirprompt() # prompt for save dir savename = name.replace(' ','-') + '_' + plot_title.replace(' ','-') \ + '_' + DATE + '.eps' filepath = os.path.join(datapath, savename) # Save figure to .eps file plt.savefig(filepath, dpi=300, format='eps', pad_inches=0) plt.show()
def add_colorbar(ax, vmin, vmax, cmap, label='', title='', orientation='horizontal', scale='linear'): #import draw.my_script as my from matplotlib.ticker import AutoLocator, LogLocator ax.set_xscale(scale) ax.set_xlim((vmin, vmax)) tickvals = ax.xaxis.get_ticklocs() ax_inv_transform = ax.transAxes.inverted().transform ax_transData = ax.transData.transform ticks = [ ax_inv_transform(ax_transData(np.array([(tic, 0.1)])))[0][0] for tic in tickvals ] #ticklabels = [my.num2str4fig(tv, scientific=False) for tv in tickvals] ticklabels = [str(tv) for tv in tickvals] ticks, ticklabels = zip( *filter(lambda x: 0.0 <= x[0] <= 1.0, zip(ticks, ticklabels))) if len(ticks) < 10: if scale == 'linear': L = AutoLocator() else: L = LogLocator(base=10, subs=np.linspace(1.0, 10.0, 10)) tkvals = L.tick_values(vmin, vmax) minticks = filter(lambda x: 0 <= x <= 1, [ ax_inv_transform(ax_transData(np.array([(tic, 0.1)])))[0][0] for tic in tkvals ]) ax.set_xscale('linear') cbar = mpl.colorbar.ColorbarBase(ax, ticklocation='auto', cmap=cmap, ticks=ticks, label=label, norm=mpl.colors.Normalize(vmin=0, vmax=1, clip=False), orientation=orientation) cbar.solids.set_rasterized(True) cbar.set_ticklabels(ticklabels) if orientation == 'horizontal': ax_working = cbar.ax.xaxis else: ax_working = cbar.ax.yaxis if len(ticks) < 10: ax_working.set_ticks([_ for _ in minticks], minor=True) ax_working.set_tick_params(which='minor', length=4) ax_working.set_tick_params(which='major', length=7) ax.set_title(title) return
for i in n: # we printen hier de progress omdat het wel even duurt om uit te rekenen if i % int((maxiter / 100)) == 0: print(" progress: " + str(int(100 * i / maxiter)) + "%", end="\r") # we rekenen elke term steeds los uit omdat dat veel dubbel rekenwerk scheelt Dfourier[i, :] = fourierterm(Dn(i, False), i, twaarden, f0waarde) Zfourier[i, :] = fourierterm(Zn(i, False), i, twaarden, f0waarde) Derror[i] = np.mean((np.sum(Dfourier, axis=0) - Dt(twaarden, f0waarde))**2) Zerror[i] = np.mean((np.sum(Zfourier, axis=0) - Zt(twaarden, f0waarde))**2) line1, = ax.plot(n, Derror, color="blue") line2, = ax.plot(n, Zerror, color="red") ax.legend([line1, line2], ["driehoeksgolf", "zaagtandgolf"]) ax.set_xlim(0, maxiter) plt.yscale("log") # deze regel maakt dat we alle machten van 10 op de y-as krijgen ax.yaxis.set_major_locator( LogLocator(base=10, subs=[1, 0], numdecs=4, numticks=15)) ax.grid(which="both", axis="both") ax.set_xlabel("$N$") ax.set_ylabel("gemiddeld kwadratisch verschil") plt.savefig("PY6-4") print("4 klaar ") # plt.show()
ax.plot(deltalist, MTE[i], color=colors_techniques[i+3], label = blabels[i], linestyle=lines[pdfls+1], lw=3) else: # ax.plot(cap, MTE[i], color=colors_techniques[i], label = techniques[i], linestyle=lines[pdfls], lw=3) ax.plot(deltalist, MTE[i], color=colors_techniques[i+1], label = blabels[i], linestyle=lines[pdfls+1], lw=3) pdfls += 1 ''' #''' #for i in range(0,len(MTE)): # ax.plot(cap[0:], MTE[i][0:], color=colourlist[i], label = blabels[i], linestyle=lines[i], lw=2) ax.tick_params(axis='both', which='major', labelsize=fnt) ######## ax.set_xlabel(r"competition mechanism $q$", fontsize=fnt) ax.set_ylabel(r"mean time to extinction $\tau_e$", fontsize=fnt) ax.set_yscale("log") #ax.set_ylim(10**(-20), 10**(0)) ax.get_yaxis().set_major_locator(LogLocator(numticks=5)) ax.minorticks_off() #ax.set_xlim(1,cap[-1]) ax.legend() #loc = 'upper right') #plt.savefig('C:\\Users\\lenov\\Pictures\\'+figname+'-q-K16.pdf',transparent=True)#, bbox_inches='tight') plt.show() #plt.savefig(DIR_OUTPUT + os.sep + figname + '.pdf', transparent=True) #plt.savefig(DIR_OUTPUT + os.sep + figname + '.eps') plt.close() """ #=======================FIGURE 5ALT========================== fig, ax = lp.newfig(0.6) MTE = []
def Plot(useexpo=True): # fetch data dateL = [] openL = [] highL = [] lowL = [] closeL = [] volumeL = [] amountL = [] ticker = '600048' start = '2016-01-01' end = '2017-02-17' today = datetime.date.today() end = today.strftime("%Y-%m-%d") if end is None else end start = (today - datetime.timedelta(days=180) ).strftime("%Y-%m-%d") if start is None else start flt = {'date': {'$gte': start, '$lt': end}} r = Daily_Db[ticker].find(flt).sort("date", pymongo.ASCENDING) for daybar in r: dateL.append(daybar['date']) openL.append(float(daybar['open'])) highL.append(float(daybar['high'])) lowL.append(float(daybar['low'])) closeL.append(float(daybar['close'])) volumeL.append(float(daybar['volume'])) amountL.append(float(daybar['amount'])) dateL = np.array(dateL) openL = np.array(openL) highL = np.array(highL) lowL = np.array(lowL) closeL = np.array(closeL) volumeL = np.array(volumeL) amountL = np.array(amountL) ma1 = ta.SMA(closeL, 2) ma5 = ta.SMA(closeL, 5) ma30 = ta.SMA(closeL, 30) pdata = pd.DataFrame({ u'日期': dateL, u'开盘': openL, u'最高': highL, u'最低': lowL, u'收盘': closeL, u'成交量': volumeL, u'1日均': ma1, u'5日均': ma5, u'30日均': ma30 }) print pdata.head(2) # 计算图片的尺寸(单位英寸) #================================================================================================================================================== length = len(pdata[u'日期']) # 所有数据的长度,就是天 highest_price = max(pdata[u'最高']) # 最高价 lowest_price = min([plow for plow in pdata[u'最低'] if plow != None]) # 最低价 yhighlim_price = round(highest_price + 1, 2) # K线子图 Y 轴最大坐标 ylowlim_price = round(lowest_price - 1, 2) # K线子图 Y 轴最小坐标 print yhighlim_price print ylowlim_price xfactor = 10.0 / 230.0 # 一条 K 线的宽度在 X 轴上所占距离(英寸) yfactor = 0.3 # Y 轴上每一个距离单位的长度(英寸),这个单位距离是线性坐标和对数坐标通用的 if useexpo: # 要使用对数坐标 expbase = 1.1 # 底数,取得小一点,比较接近 1。股价 3 元到 4 元之间有大约 3 个单位距离 ymulti_price = math.log(yhighlim_price, expbase) - math.log( ylowlim_price, expbase) # 价格在 Y 轴上的 “份数” else: ymulti_price = (yhighlim_price - ylowlim_price) / 100 # 价格在 Y 轴上的 “份数” ymulti_vol = 3.0 # 成交量部分在 Y 轴所占的 “份数” ymulti_top = 0.2 # 顶部空白区域在 Y 轴所占的 “份数” ymulti_bot = 0.8 # 底部空白区域在 Y 轴所占的 “份数” xmulti_left = 10.0 # 左侧空白区域所占的 “份数” xmulti_right = 3.0 # 右侧空白区域所占的 “份数” xmulti_all = length + xmulti_left + xmulti_right xlen_fig = xmulti_all * xfactor # 整个 Figure 的宽度 ymulti_all = ymulti_price + ymulti_vol + ymulti_top + ymulti_bot ylen_fig = ymulti_all * yfactor # 整个 Figure 的高度 rect_1 = (xmulti_left / xmulti_all, (ymulti_bot + ymulti_vol) / ymulti_all, length / xmulti_all, ymulti_price / ymulti_all) # K线图部分 rect_2 = (xmulti_left / xmulti_all, ymulti_bot / ymulti_all, length / xmulti_all, ymulti_vol / ymulti_all) # 成交量部分 # 建立 Figure 对象 #================================================================================================================================================== figfacecolor = 'white' figedgecolor = 'black' figdpi = 600 figlinewidth = 1.0 figobj = plt.figure(figsize=(xlen_fig, ylen_fig), dpi=figdpi, facecolor=figfacecolor, edgecolor=figedgecolor, linewidth=figlinewidth) # Figure 对象 #================================================================================================================================================== #================================================================================================================================================== #======= 成交量部分 #================================================================================================================================================== #================================================================================================================================================== # 添加 Axes 对象 #================================================================================================================================================== axes_2 = figobj.add_axes(rect_2, facecolor='black') axes_2.set_axisbelow(True) # 网格线放在底层 # 改变坐标线的颜色 #================================================================================================================================================== for child in axes_2.get_children(): if isinstance(child, matplotlib.spines.Spine): child.set_color('lightblue') # 得到 X 轴 和 Y 轴 的两个 Axis 对象 #================================================================================================================================================== xaxis_2 = axes_2.get_xaxis() yaxis_2 = axes_2.get_yaxis() # 设置两个坐标轴上的 grid #================================================================================================================================================== xaxis_2.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2) xaxis_2.grid(True, 'minor', color='0.3', linestyle='dotted', linewidth=0.1) yaxis_2.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2) yaxis_2.grid(True, 'minor', color='0.3', linestyle='dotted', linewidth=0.1) #================================================================================================================================================== #======= 绘图 #================================================================================================================================================== xindex = np.arange(length) # X 轴上的 index,一个辅助数据 zipoc = zip(pdata[u'开盘'], pdata[u'收盘']) up = np.array([ True if po < pc and po != None else False for po, pc in zipoc ]) # 标示出该天股价日内上涨的一个序列 down = np.array([ True if po > pc and po != None else False for po, pc in zipoc ]) # 标示出该天股价日内下跌的一个序列 side = np.array([ True if po == pc and po != None else False for po, pc in zipoc ]) # 标示出该天股价日内走平的一个序列 volume = pdata[u'成交量'] rarray_vol = np.array(volume) volzeros = np.zeros(length) # 辅助数据 # XXX: 如果 up/down/side 各项全部为 False,那么 vlines() 会报错。 if True in up: axes_2.vlines(xindex[up], volzeros[up], rarray_vol[up], color='red', linewidth=3.0, label='_nolegend_') if True in down: axes_2.vlines(xindex[down], volzeros[down], rarray_vol[down], color='green', linewidth=3.0, label='_nolegend_') if True in side: axes_2.vlines(xindex[side], volzeros[side], rarray_vol[side], color='0.7', linewidth=3.0, label='_nolegend_') # 设定 X 轴坐标的范围 #================================================================================================================================================== axes_2.set_xlim(-1, length) # 设定 X 轴上的坐标 #================================================================================================================================================== #datelist= [ datetime.date(int(ys), int(ms), int(ds)) for ys, ms, ds in [ dstr.split('-') for dstr in pdata[u'日期'] ] ] datelist = [ datetime.datetime.strptime(dstr, "%Y-%m-%d") for dstr in pdata[u'日期'] ] # 确定 X 轴的 MajorLocator mdindex = [] # 每个月第一个交易日在所有日期列表中的 index years = set([d.year for d in datelist]) # 所有的交易年份 for y in sorted(years): months = set([d.month for d in datelist if d.year == y]) # 当年所有的交易月份 for m in sorted(months): monthday = min([ dt for dt in datelist if dt.year == y and dt.month == m ]) # 当月的第一个交易日 mdindex.append(datelist.index(monthday)) xMajorLocator = FixedLocator(np.array(mdindex)) # 确定 X 轴的 MinorLocator wdindex = [] # 每周第一个交易日在所有日期列表中的 index for d in datelist: if d.weekday() == 0: wdindex.append(datelist.index(d)) xMinorLocator = FixedLocator(np.array(wdindex)) # 确定 X 轴的 MajorFormatter 和 MinorFormatter def x_major_formatter_2(idx, pos=None): print idx return datelist[int(idx)].strftime('%Y-%m-%d') def x_minor_formatter_2(idx, pos=None): return datelist[idx].strftime('%m-%d') xMajorFormatter = FuncFormatter(x_major_formatter_2) xMinorFormatter = FuncFormatter(x_minor_formatter_2) # 设定 X 轴的 Locator 和 Formatter xaxis_2.set_major_locator(xMajorLocator) xaxis_2.set_major_formatter(xMajorFormatter) xaxis_2.set_minor_locator(xMinorLocator) xaxis_2.set_minor_formatter(xMinorFormatter) # 设定 X 轴主要坐标点与辅助坐标点的样式 for malabel in axes_2.get_xticklabels(minor=False): malabel.set_fontsize(3) malabel.set_horizontalalignment('right') malabel.set_rotation('30') for milabel in axes_2.get_xticklabels(minor=True): milabel.set_fontsize(2) milabel.set_horizontalalignment('right') milabel.set_rotation('30') # 设定 Y 轴坐标的范围 #================================================================================================================================================== maxvol = max(volume) # 注意是 int 类型 axes_2.set_ylim(0, maxvol) # 设定 Y 轴上的坐标 #================================================================================================================================================== vollen = len(str(maxvol)) yMajorLocator_2 = MultipleLocator(10**(vollen - 1)) yMinorLocator_2 = MultipleLocator((10**(vollen - 2)) * 5) # 确定 Y 轴的 MajorFormatter # def y_major_formatter_2(num, pos=None): # numtable= {'1':u'一', '2':u'二', '3':u'三', '4':u'四', '5':u'五', '6':u'六', '7':u'七', '8':u'八', '9':u'九', } # dimtable= {3:u'百', 4:u'千', 5:u'万', 6:u'十万', 7:u'百万', 8:u'千万', 9:u'亿', 10:u'十亿', 11:u'百亿'} # return numtable[str(num)[0]] + dimtable[vollen] if num != 0 else '0' def y_major_formatter_2(num, pos=None): return int(num) yMajorFormatter_2 = FuncFormatter(y_major_formatter_2) # 确定 Y 轴的 MinorFormatter # def y_minor_formatter_2(num, pos=None): # return int(num) # yMinorFormatter_2= FuncFormatter(y_minor_formatter_2) yMinorFormatter_2 = NullFormatter() # 设定 X 轴的 Locator 和 Formatter yaxis_2.set_major_locator(yMajorLocator_2) yaxis_2.set_major_formatter(yMajorFormatter_2) yaxis_2.set_minor_locator(yMinorLocator_2) yaxis_2.set_minor_formatter(yMinorFormatter_2) # 设定 Y 轴主要坐标点与辅助坐标点的样式 for malab in axes_2.get_yticklabels(minor=False): malab.set_fontsize(3) for milab in axes_2.get_yticklabels(minor=True): milab.set_fontsize(2) #================================================================================================================================================== #================================================================================================================================================== #======= K 线图部分 #================================================================================================================================================== #================================================================================================================================================== # 添加 Axes 对象 #================================================================================================================================================== axes_1 = figobj.add_axes(rect_1, facecolor='black', sharex=axes_2) axes_1.set_axisbelow(True) # 网格线放在底层 if useexpo: axes_1.set_yscale('log', basey=expbase) # 使用对数坐标 # 改变坐标线的颜色 #================================================================================================================================================== for child in axes_1.get_children(): if isinstance(child, matplotlib.spines.Spine): child.set_color('lightblue') # 得到 X 轴 和 Y 轴 的两个 Axis 对象 #================================================================================================================================================== xaxis_1 = axes_1.get_xaxis() yaxis_1 = axes_1.get_yaxis() # 设置两个坐标轴上的 grid #================================================================================================================================================== xaxis_1.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2) xaxis_1.grid(True, 'minor', color='0.3', linestyle='dotted', linewidth=0.1) yaxis_1.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2) yaxis_1.grid(True, 'minor', color='0.3', linestyle='dotted', linewidth=0.1) #================================================================================================================================================== #======= 绘图 #================================================================================================================================================== # 绘制 K 线部分 #================================================================================================================================================== rarray_open = np.array(pdata[u'开盘']) rarray_close = np.array(pdata[u'收盘']) rarray_high = np.array(pdata[u'最高']) rarray_low = np.array(pdata[u'最低']) # XXX: 如果 up, down, side 里有一个全部为 False 组成,那么 vlines() 会报错。 if True in up: axes_1.vlines(xindex[up], rarray_low[up], rarray_high[up], color='red', linewidth=0.6, label='_nolegend_') axes_1.vlines(xindex[up], rarray_open[up], rarray_close[up], color='red', linewidth=3.0, label='_nolegend_') if True in down: axes_1.vlines(xindex[down], rarray_low[down], rarray_high[down], color='green', linewidth=0.6, label='_nolegend_') axes_1.vlines(xindex[down], rarray_open[down], rarray_close[down], color='green', linewidth=3.0, label='_nolegend_') if True in side: axes_1.vlines(xindex[side], rarray_low[side], rarray_high[side], color='0.7', linewidth=0.6, label='_nolegend_') axes_1.vlines(xindex[side], rarray_open[side], rarray_close[side], color='0.7', linewidth=3.0, label='_nolegend_') # 绘制均线部分 #================================================================================================================================================== rarray_1dayave = np.array(pdata[u'1日均']) rarray_5dayave = np.array(pdata[u'5日均']) rarray_30dayave = np.array(pdata[u'30日均']) axes_1.plot(xindex, rarray_1dayave, 'o-', color='white', linewidth=0.1, markersize=0.7, markeredgecolor='white', markeredgewidth=0.1) # 1日加权均线 axes_1.plot(xindex, rarray_5dayave, 'o-', color='yellow', linewidth=0.1, markersize=0.7, markeredgecolor='yellow', markeredgewidth=0.1) # 5日均线 axes_1.plot(xindex, rarray_30dayave, 'o-', color='green', linewidth=0.1, markersize=0.7, markeredgecolor='green', markeredgewidth=0.1) # 30日均线 # 设定 X 轴坐标的范围 #================================================================================================================================================== axes_1.set_xlim(-1, length) # 先设置 label 位置,再将 X 轴上的坐标设为不可见。因为与 成交量子图 共用 X 轴 #================================================================================================================================================== # 设定 X 轴的 Locator 和 Formatter xaxis_1.set_major_locator(xMajorLocator) xaxis_1.set_major_formatter(xMajorFormatter) xaxis_1.set_minor_locator(xMinorLocator) xaxis_1.set_minor_formatter(xMinorFormatter) # 将 X 轴上的坐标设为不可见。 for malab in axes_1.get_xticklabels(minor=False): malab.set_visible(False) for milab in axes_1.get_xticklabels(minor=True): milab.set_visible(False) # 用这一段效果也一样 # plt.setp(axes_1.get_xticklabels(minor=False), visible=False) # plt.setp(axes_1.get_xticklabels(minor=True), visible=False) # 设定 Y 轴坐标的范围 #================================================================================================================================================== axes_1.set_ylim(ylowlim_price, yhighlim_price) # 设定 Y 轴上的坐标 #================================================================================================================================================== if useexpo: # 主要坐标点 #----------------------------------------------------- yMajorLocator_1 = LogLocator(base=expbase) yMajorFormatter_1 = NullFormatter() # 设定 X 轴的 Locator 和 Formatter yaxis_1.set_major_locator(yMajorLocator_1) yaxis_1.set_major_formatter(yMajorFormatter_1) # 设定 Y 轴主要坐标点与辅助坐标点的样式 # for mal in axes_1.get_yticklabels(minor=False): # mal.set_fontsize(3) # 辅助坐标点 #----------------------------------------------------- minorticks = range(int(ylowlim_price), int(yhighlim_price) + 1, 100) yMinorLocator_1 = FixedLocator(np.array(minorticks)) # 确定 Y 轴的 MinorFormatter def y_minor_formatter_1(num, pos=None): return str(num / 100.0) + '0' yMinorFormatter_1 = FuncFormatter(y_minor_formatter_1) # 设定 X 轴的 Locator 和 Formatter yaxis_1.set_minor_locator(yMinorLocator_1) yaxis_1.set_minor_formatter(yMinorFormatter_1) # 设定 Y 轴主要坐标点与辅助坐标点的样式 for mil in axes_1.get_yticklabels(minor=True): mil.set_fontsize(3) else: # 如果使用线性坐标,那么只标主要坐标点 yMajorLocator_1 = MultipleLocator(100) def y_major_formatter_1(num, pos=None): return str(num / 100.0) + '0' yMajorFormatter_1 = FuncFormatter(y_major_formatter_1) # 设定 Y 轴的 Locator 和 Formatter yaxis_1.set_major_locator(yMajorLocator_1) yaxis_1.set_major_formatter(yMajorFormatter_1) # 设定 Y 轴主要坐标点与辅助坐标点的样式 for mal in axes_1.get_yticklabels(minor=False): mal.set_fontsize(3) # 保存图片 #================================================================================================================================================== #figobj.savefig(figpath, dpi=figdpi, facecolor=figfacecolor, edgecolor=figedgecolor, linewidth=figlinewidth) plt.show()
def create_plot(xData, yData, xAxisRange, yAxisRange, xAxisLabel, yAxisLabel, dataLabel, plotPosition, subplotPositions, logScale=[False, False], tickLabels=[True, True], axisLabels=[True, True], addLegend=False, color=False, style=False, linewidth=1.0): subplot = pyplot.subplot(subplotPositions[plotPosition - 1]) # Create a list of colour and line styles for the datasets, if not specified in the call if not color: color = [ 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple', 'red', 'orange', 'green', 'blue', 'purple' ] if not style: style = [ 'solid', 'solid', 'solid', 'solid', 'solid', 'dashed', 'dashed', 'dashed', 'dashed', 'dashed', 'dotted', 'dotted', 'dotted', 'dotted', 'dotted', 'dashdot', 'dashdot', 'dashdot', 'dashdot', 'dashdot', 'solid', 'solid', 'solid', 'solid', 'solid', 'dashed', 'dashed', 'dashed', 'dashed', 'dashed', 'dotted', 'dotted', 'dotted', 'dotted', 'dotted', 'dashdot', 'dashdot', 'dashdot', 'dashdot', 'dashdot', 'solid', 'solid', 'solid', 'solid', 'solid', 'dashed', 'dashed', 'dashed', 'dashed', 'dashed', 'dotted', 'dotted', 'dotted', 'dotted', 'dotted', 'dashdot', 'dashdot', 'dashdot', 'dashdot', 'dashdot' ] # Plot each dataset plottedLines = [] for n in range(len(yData)): plot = pyplot.plot(xData, yData[n], color=color[n], linestyle=style[n], linewidth=1.0, label=dataLabel[n]) # Set the axes scales, ranges and tickmarks if logScale[0]: pyplot.xscale('log') if logScale[1]: pyplot.yscale('log') pyplot.axis([ xAxisRange[0][0], xAxisRange[0][1], yAxisRange[0][0], yAxisRange[0][1] ]) if logScale[0]: subplot.xaxis.set_major_locator(LogLocator(base=xAxisRange[1][0])) subplot.xaxis.set_minor_locator( LogLocator(base=xAxisRange[1][0], subs=range(int(xAxisRange[1][0] / xAxisRange[1][1])))) else: subplot.xaxis.set_major_locator(MultipleLocator(xAxisRange[1][0])) subplot.xaxis.set_minor_locator(MultipleLocator(xAxisRange[1][1])) if logScale[1]: subplot.yaxis.set_major_locator(LogLocator(base=yAxisRange[1][0])) subplot.yaxis.set_minor_locator( LogLocator(base=yAxisRange[1][0], subs=range(int(yAxisRange[1][0] / yAxisRange[1][1])))) else: subplot.yaxis.set_major_locator(MultipleLocator(yAxisRange[1][0])) subplot.yaxis.set_minor_locator(MultipleLocator(yAxisRange[1][1])) # Add tick and axis labels, if requested if not tickLabels[0]: pyplot.tick_params(axis='x', labelbottom='off') if not tickLabels[1]: pyplot.tick_params(axis='y', labelleft='off') if axisLabels[0]: pyplot.xlabel(xAxisLabel) if axisLabels[1]: pyplot.ylabel(yAxisLabel) # Add a legend, if requested if addLegend: pyplot.legend(mode='expand', loc='best', frameon=False, prop={'size': 10}, borderpad=0, labelspacing=0.1, handletextpad=0.1, borderaxespad=0.6, handlelength=2.4) return plot
def add_colorbar(self, mappable=None, ax=None, location='right', width=0.2, pad=0.1, log=None, label="", clim=None, cmap=None, clip=None, visible=True, axes_class=axes.Axes, **kwargs): """Add a colorbar to the current `Axes` Parameters ---------- mappable : matplotlib data collection collection against which to map the colouring ax : :class:`~matplotlib.axes.Axes` axes from which to steal space for the colour-bar location : `str`, optional, default: 'right' position of the colorbar width : `float`, optional default: 0.2 width of the colorbar as a fraction of the axes pad : `float`, optional, default: 0.1 gap between the axes and the colorbar as a fraction of the axes log : `bool`, optional, default: `False` display the colorbar with a logarithmic scale label : `str`, optional, default: '' (no label) label for the colorbar clim : pair of floats, optional (lower, upper) limits for the colorbar scale, values outside of these limits will be clipped to the edges visible : `bool`, optional, default: `True` make the colobar visible on the figure, this is useful to make two plots, each with and without a colorbar, but guarantee that the axes will be the same size **kwargs other keyword arguments to be passed to the :meth:`~matplotlib.figure.Figure.colorbar` generator Returns ------- Colorbar the :class:`~matplotlib.colorbar.Colorbar` added to this plot """ # find default layer if mappable is None and ax is not None and len(ax.collections): mappable = ax.collections[-1] elif mappable is None and ax is not None and len(ax.images): mappable = ax.images[-1] elif (visible is False and mappable is None and ax is not None and len(ax.lines)): mappable = ax.lines[-1] elif mappable is None and ax is None: for ax in self.axes[::-1]: if hasattr(ax, 'collections') and len(ax.collections): mappable = ax.collections[-1] break elif hasattr(ax, 'images') and len(ax.images): mappable = ax.images[-1] break elif visible is False and len(ax.lines): mappable = ax.lines[-1] break if visible and mappable is None: raise ValueError("Cannot determine mappable layer for this " "colorbar") elif ax is None: raise ValueError("Cannot determine an anchor Axes for this " "colorbar") # find default axes if not ax: ax = mappable.axes mappables = ax.collections + ax.images # get new colour axis divider = make_axes_locatable(ax) if location not in ['right', 'top']: raise ValueError("'left' and 'bottom' colorbars have not " "been implemented") cax = divider.append_axes(location, width, pad=pad, add_to_figure=visible, axes_class=axes_class) self._coloraxes.append(cax) if visible: self.sca(ax) else: return # set limits if not clim: clim = mappable.get_clim() if log is None: log = isinstance(mappable.norm, mcolors.LogNorm) if log and clim[0] <= 0.0: cdata = mappable.get_array() try: clim = (cdata[cdata > 0.0].min(), clim[1]) except ValueError: pass for m in mappables: m.set_clim(clim) # set map if cmap is not None: mappable.set_cmap(cmap) # set normalisation norm = mappable.norm if clip is None: clip = norm.clip for m in mappables: if log and not isinstance(norm, mcolors.LogNorm): m.set_norm(mcolors.LogNorm(*mappable.get_clim())) elif not log: m.set_norm(mcolors.Normalize(*mappable.get_clim())) m.norm.clip = clip # set log ticks if log: kwargs.setdefault('ticks', LogLocator(subs=numpy.arange(1, 11))) kwargs.setdefault('format', CombinedLogFormatterMathtext()) # make colour bar colorbar = self.colorbar(mappable, cax=cax, ax=ax, **kwargs) # set label if label: colorbar.set_label(label) colorbar.draw_all() self.colorbars.append(colorbar) return colorbar
ntot = 0.0 * nHtot for i in range(3, 4 + NELEM + NMOLE): # electrons, all atoms, ions and cations ntot = ntot + 10**dat[:, i] logntot = np.log10(ntot) colo = [ 'blue', 'black', 'silver', 'red', 'darkorange', 'gold', 'darkorchid', 'aqua', 'cadetblue', 'cornflowerblue', 'chartreuse', 'limegreen', 'darkgreen', 'chocolate', 'darkgoldenrod', 'darkkhaki', 'pink', 'moccasin' ] #'darkolivegreen','darkmagenta','aquamarine','coral','burlywood', #'beige','darkorange','crimson','darkcyan','bisque' Ncolor = len(colo) colo = colo * 10 styl = ['-'] * Ncolor + ['--'] * Ncolor + [':'] * Ncolor + ['-.'] * Ncolor * 7 widt = [2] * Ncolor * 10 locmin = LogLocator(base=10.0, subs=(0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)) locmaj = np.array([100, 200, 500, 1000, 2000, 5000, 10000]) locmaj = locmaj[np.where(locmaj <= Tmax)[0]] locmaj = locmaj[np.where(locmaj >= Tmin)[0]] #================== pressure structure ==================== fig, ax = plt.subplots(figsize=(6.5, 5.5)) plt.plot(press / bar, zz, lw=4) plt.ylabel(r'$z\ \mathrm{[km]}$', fontsize=20) plt.xlabel(r'$p\ \mathrm{[bar]}$', fontsize=20) plt.xscale('log') plt.xlim(pmin, pmax) plt.ylim(zmin, zmax) plt.tight_layout() plt.savefig(pp, format='pdf') plt.clf()
def plot_results(bestbeam, times, fratio_max, baz, app_vel, snr, stream=None, origintime=None, distance=None, utctime=False, vmin=None, vmax=None): """ Quick and dirty plotting function to preview beamforming results. Parameters ---------- bestbeam : :class:`~obspy.core.trace.Trace` A :class:`~obspy.core.trace.Trace` object containing the bestbeam. times : :class:`~numpy.ndarray` Time since start time of `stream`. Represents the middle of each time window. fratio_max : :class:`~numpy.ndarray` The maximum F-ratio in each time window. baz : :class:`~numpy.ndarray` The bearing from which the wavefront arrives, aka: back-azimuth. app_vel : :class:`~numpy.ndarray` The horizontal velocity at which the wavefront propagated over the array. snr : :class:`~numpy.ndarray` The signal-to-noise ratio. stream : :class:`~obspy.core.stream.Stream` A :class:`~obspy.core.stream.Stream` object containing the data used for beamforming. Traces will be plotted in the background behind the bestbeam. origintime : :class:`~obspy.core.utcdatetime.UTCDateTime` Origin time of the source. distance : float Source-receiver distance in km. utctime : bool Plot time axis in UTC. Note ---- If both `origintime` and `distance` are not ``None``, a celerity axes will be plotted above the top axes. """ origintime = origintime or 0 t_offset = bestbeam.stats.starttime - origintime if utctime: t_offset = 0 origintime = None bestbeam_times = bestbeam.times('matplotlib') detection_times = times / 86400. + bestbeam_times[0] else: bestbeam_times = bestbeam.times('relative', origintime) detection_times = times + t_offset fig, ax = plt.subplots(5, figsize=(7, 8), sharex=True) if origintime and distance: plot_celerities(celerities, distance, ax[0]) im = spectrogram(bestbeam, t_offset, ax=ax[0], cmap='Greys', utctime=utctime) data_ = im.get_array() im.set_clim(0.1 * data_.std(), 0.85 * data_.max()) cb1 = plt.colorbar(im, ax=ax[0], extend='both', pad=0.02, aspect=10, label='Power') ax[0].set_yscale('log') ax[0].yaxis.set_major_locator(LogLocator(numticks=4)) ax[0].yaxis.set_minor_locator(LogLocator(subs='all', numticks=10)) ax[0].yaxis.set_minor_formatter(NullFormatter()) ax[0].set_ylabel('Frequency, Hz') try: for tr in stream: if utctime: ax[1].plot(tr.times('matplotlib'), tr.data, lw=0.5, alpha=0.3) else: ax[1].plot(tr.times('relative', origintime), tr.data, lw=0.5, alpha=0.3) except TypeError: pass ax[1].plot(bestbeam_times, bestbeam.data, 'k', lw=0.5) ax[1].set_ylabel('Amplitude') cb_fake = plt.colorbar(im, ax=ax[1:-1], extend='both', pad=0.02, aspect=10) cb_fake.remove() vmax = vmax or 0.85 * snr.max() vmin = vmin or 0.6 cmap = plt.get_cmap('inferno_r') cmap.set_under('w') sort_indices = snr.argsort() custom_scatter(detection_times[sort_indices], baz[sort_indices], ax[2], s=15, c=snr[sort_indices], cmap=cmap, vmin=vmin, vmax=vmax, edgecolor='k', lw=0.5) ax[2].set_ylim(0, 360) ax[2].set_ylabel(u'Back azimuth, °') custom_scatter(detection_times[sort_indices], app_vel[sort_indices], ax[3], s=15, c=snr[sort_indices], cmap=cmap, vmin=vmin, vmax=vmax, edgecolor='k', lw=0.5) ax[3].set_ylabel('App. vel., m/s') sp = custom_scatter(detection_times[sort_indices], fratio_max[sort_indices], ax[4], s=15, c=snr[sort_indices], cmap=cmap, vmin=vmin, vmax=vmax, edgecolor='k', lw=0.5) ax[4].set_ylabel('F-ratio') if utctime: for axi in ax: axi.xaxis_date() ax[4].set_xlabel('Time (UTC)') # fig.autofmt_xdate() elif origintime: ax[4].set_xlabel('Time since origin {}'.format( origintime.strftime('%FT%T'))) else: ax[4].set_xlabel('Time since {}'.format( bestbeam.stats.starttime.strftime('%FT%T'))) cb2 = plt.colorbar(sp, ax=ax[-1], extend='both', pad=0.02, aspect=10, label='SNR') for axi in ax: axi.grid(True, axis='x', lw=0.5, color='0.7') axi.yaxis.set_label_coords(-0.1, 0.5) ax[4].set_xlim(bestbeam_times[0], bestbeam_times[-1]) ax[0].set_title('Beamforming results', y=1.4) return fig, ax, cb1, cb2
# x, y = 1750, df["xsec_pb"].iloc[-1] # print(x,y) y *= 0.8 if "_stopsbottom_" in filename: y *= 0.4 ax.text(x, y, latex, color=color, rotation=-30, fontsize=14) # draw legend and style plot ax.set_xlabel("particle mass [GeV]") ax.set_ylabel("cross section [fb]") ax.set_yscale("log") ax.grid(True) ax.set_xlim(100, 2500) ax.set_ylim(1e-5 * 1e3, 1e2 * 1e3) # ax.legend(ncol = 2, framealpha = 1) # ax.legend(ncol = 2) # ax.locator_params(axis = "y", base = 100) # for log-scaled axis, it's LogLocator, not MaxNLocator from matplotlib.ticker import MultipleLocator, LogLocator, NullFormatter ax.set_title( "$\mathit{pp}$, $\sqrt{\mathit{s}}$ = 13 TeV, NLO+NLL - NNLO$_\mathregular{approx}$+NNLL", fontsize=12) ax.xaxis.set_minor_locator(MultipleLocator(100.)) ax.yaxis.set_major_locator(LogLocator(base=10., subs=(1., ))) ax.yaxis.set_minor_locator(LogLocator(base=10., subs=np.arange(2, 10) * 0.1)) fig.set_tight_layout(True) fig.savefig("plot_susy_xsecs.pdf") os.system("ic plot_susy_xsecs.pdf")
def Plot(pfile, figpath, useexpo=True): ''' pfile 指明存放绘图数据的 pickle file,figpath 指定图片需存放的路径 ''' fileobj = open(name=pfile, mode='rb') pdata = pickle.load(fileobj) fileobj.close() # 计算图片的尺寸(单位英寸) # 注意:Python2 里面, "1 / 10" 结果是 0, 必须写成 "1.0 / 10" 才会得到 0.1 #================================================================================================================================================== length = len(pdata[u'日期']) # 所有数据的长度,就是天数 highest_price = max(pdata[u'最高']) # 最高价 lowest_price = min([plow for plow in pdata[u'最低'] if plow != None]) # 最低价 yhighlim_price = round(highest_price + 50, -2) # K线子图 Y 轴最大坐标 ylowlim_price = round(lowest_price - 50, -2) # K线子图 Y 轴最小坐标 xfactor = 10.0 / 230.0 # 一条 K 线的宽度在 X 轴上所占距离(英寸) yfactor = 0.3 # Y 轴上每一个距离单位的长度(英寸),这个单位距离是线性坐标和对数坐标通用的 if useexpo: # 要使用对数坐标 expbase = 1.1 # 底数,取得小一点,比较接近 1。股价 3 元到 4 元之间有大约 3 个单位距离 ymulti_price = math.log(yhighlim_price, expbase) - math.log( ylowlim_price, expbase) # 价格在 Y 轴上的 “份数” else: ymulti_price = (yhighlim_price - ylowlim_price) / 100 # 价格在 Y 轴上的 “份数” ymulti_vol = 3.0 # 成交量部分在 Y 轴所占的 “份数” ymulti_top = 0.2 # 顶部空白区域在 Y 轴所占的 “份数” ymulti_bot = 0.8 # 底部空白区域在 Y 轴所占的 “份数” xmulti_left = 10.0 # 左侧空白区域所占的 “份数” xmulti_right = 3.0 # 右侧空白区域所占的 “份数” xmulti_all = length + xmulti_left + xmulti_right xlen_fig = xmulti_all * xfactor # 整个 Figure 的宽度 ymulti_all = ymulti_price + ymulti_vol + ymulti_top + ymulti_bot ylen_fig = ymulti_all * yfactor # 整个 Figure 的高度 rect_1 = (xmulti_left / xmulti_all, (ymulti_bot + ymulti_vol) / ymulti_all, length / xmulti_all, ymulti_price / ymulti_all) # K线图部分 rect_2 = (xmulti_left / xmulti_all, ymulti_bot / ymulti_all, length / xmulti_all, ymulti_vol / ymulti_all) # 成交量部分 # 建立 Figure 对象 #================================================================================================================================================== figfacecolor = 'white' figedgecolor = 'black' figdpi = 600 figlinewidth = 1.0 figobj = pyplot.figure(figsize=(xlen_fig, ylen_fig), dpi=figdpi, facecolor=figfacecolor, edgecolor=figedgecolor, linewidth=figlinewidth) # Figure 对象 #================================================================================================================================================== #================================================================================================================================================== #======= 成交量部分 #================================================================================================================================================== #================================================================================================================================================== # 添加 Axes 对象 #================================================================================================================================================== axes_2 = figobj.add_axes(rect_2, axis_bgcolor='black') axes_2.set_axisbelow(True) # 网格线放在底层 # 改变坐标线的颜色 #================================================================================================================================================== for child in axes_2.get_children(): if isinstance(child, matplotlib.spines.Spine): child.set_color('lightblue') # 得到 X 轴 和 Y 轴 的两个 Axis 对象 #================================================================================================================================================== xaxis_2 = axes_2.get_xaxis() yaxis_2 = axes_2.get_yaxis() # 设置两个坐标轴上的 grid #================================================================================================================================================== xaxis_2.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2) xaxis_2.grid(True, 'minor', color='0.3', linestyle='dotted', linewidth=0.1) yaxis_2.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2) yaxis_2.grid(True, 'minor', color='0.3', linestyle='dotted', linewidth=0.1) #================================================================================================================================================== #======= 绘图 #================================================================================================================================================== xindex = numpy.arange(length) # X 轴上的 index,一个辅助数据 zipoc = zip(pdata[u'开盘'], pdata[u'收盘']) up = numpy.array([ True if po < pc and po != None else False for po, pc in zipoc ]) # 标示出该天股价日内上涨的一个序列 down = numpy.array([ True if po > pc and po != None else False for po, pc in zipoc ]) # 标示出该天股价日内下跌的一个序列 side = numpy.array([ True if po == pc and po != None else False for po, pc in zipoc ]) # 标示出该天股价日内走平的一个序列 volume = pdata[u'成交量'] rarray_vol = numpy.array(volume) volzeros = numpy.zeros(length) # 辅助数据 # XXX: 如果 up/down/side 各项全部为 False,那么 vlines() 会报错。 if True in up: axes_2.vlines(xindex[up], volzeros[up], rarray_vol[up], color='red', linewidth=3.0, label='_nolegend_') if True in down: axes_2.vlines(xindex[down], volzeros[down], rarray_vol[down], color='green', linewidth=3.0, label='_nolegend_') if True in side: axes_2.vlines(xindex[side], volzeros[side], rarray_vol[side], color='0.7', linewidth=3.0, label='_nolegend_') # 设定 X 轴坐标的范围 #================================================================================================================================================== axes_2.set_xlim(-1, length) # 设定 X 轴上的坐标 #================================================================================================================================================== datelist = [ datetime.date(int(ys), int(ms), int(ds)) for ys, ms, ds in [dstr.split('-') for dstr in pdata[u'日期']] ] # 确定 X 轴的 MajorLocator mdindex = [] # 每个月第一个交易日在所有日期列表中的 index years = set([d.year for d in datelist]) # 所有的交易年份 for y in sorted(years): months = set([d.month for d in datelist if d.year == y]) # 当年所有的交易月份 for m in sorted(months): monthday = min([ dt for dt in datelist if dt.year == y and dt.month == m ]) # 当月的第一个交易日 mdindex.append(datelist.index(monthday)) xMajorLocator = FixedLocator(numpy.array(mdindex)) # 确定 X 轴的 MinorLocator wdindex = [] # 每周第一个交易日在所有日期列表中的 index for d in datelist: if d.weekday() == 0: wdindex.append(datelist.index(d)) xMinorLocator = FixedLocator(numpy.array(wdindex)) # 确定 X 轴的 MajorFormatter 和 MinorFormatter def x_major_formatter_2(idx, pos=None): return datelist[idx].strftime('%Y-%m-%d') def x_minor_formatter_2(idx, pos=None): return datelist[idx].strftime('%m-%d') xMajorFormatter = FuncFormatter(x_major_formatter_2) xMinorFormatter = FuncFormatter(x_minor_formatter_2) # 设定 X 轴的 Locator 和 Formatter xaxis_2.set_major_locator(xMajorLocator) xaxis_2.set_major_formatter(xMajorFormatter) xaxis_2.set_minor_locator(xMinorLocator) xaxis_2.set_minor_formatter(xMinorFormatter) # 设定 X 轴主要坐标点与辅助坐标点的样式 for malabel in axes_2.get_xticklabels(minor=False): malabel.set_fontsize(3) malabel.set_horizontalalignment('right') malabel.set_rotation('30') for milabel in axes_2.get_xticklabels(minor=True): milabel.set_fontsize(2) milabel.set_horizontalalignment('right') milabel.set_rotation('30') # 设定 Y 轴坐标的范围 #================================================================================================================================================== maxvol = max(volume) # 注意是 int 类型 axes_2.set_ylim(0, maxvol) # 设定 Y 轴上的坐标 #================================================================================================================================================== vollen = len(str(maxvol)) yMajorLocator_2 = MultipleLocator(10**(vollen - 1)) yMinorLocator_2 = MultipleLocator((10**(vollen - 2)) * 5) # 确定 Y 轴的 MajorFormatter # def y_major_formatter_2(num, pos=None): # numtable= {'1':u'一', '2':u'二', '3':u'三', '4':u'四', '5':u'五', '6':u'六', '7':u'七', '8':u'八', '9':u'九', } # dimtable= {3:u'百', 4:u'千', 5:u'万', 6:u'十万', 7:u'百万', 8:u'千万', 9:u'亿', 10:u'十亿', 11:u'百亿'} # return numtable[str(num)[0]] + dimtable[vollen] if num != 0 else '0' def y_major_formatter_2(num, pos=None): return int(num) yMajorFormatter_2 = FuncFormatter(y_major_formatter_2) # 确定 Y 轴的 MinorFormatter # def y_minor_formatter_2(num, pos=None): # return int(num) # yMinorFormatter_2= FuncFormatter(y_minor_formatter_2) yMinorFormatter_2 = NullFormatter() # 设定 X 轴的 Locator 和 Formatter yaxis_2.set_major_locator(yMajorLocator_2) yaxis_2.set_major_formatter(yMajorFormatter_2) yaxis_2.set_minor_locator(yMinorLocator_2) yaxis_2.set_minor_formatter(yMinorFormatter_2) # 设定 Y 轴主要坐标点与辅助坐标点的样式 for malab in axes_2.get_yticklabels(minor=False): malab.set_fontsize(3) for milab in axes_2.get_yticklabels(minor=True): milab.set_fontsize(2) #================================================================================================================================================== #================================================================================================================================================== #======= K 线图部分 #================================================================================================================================================== #================================================================================================================================================== # 添加 Axes 对象 #================================================================================================================================================== axes_1 = figobj.add_axes(rect_1, axis_bgcolor='black', sharex=axes_2) axes_1.set_axisbelow(True) # 网格线放在底层 if useexpo: axes_1.set_yscale('log', basey=expbase) # 使用对数坐标 # 改变坐标线的颜色 #================================================================================================================================================== for child in axes_1.get_children(): if isinstance(child, matplotlib.spines.Spine): child.set_color('lightblue') # 得到 X 轴 和 Y 轴 的两个 Axis 对象 #================================================================================================================================================== xaxis_1 = axes_1.get_xaxis() yaxis_1 = axes_1.get_yaxis() # 设置两个坐标轴上的 grid #================================================================================================================================================== xaxis_1.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2) xaxis_1.grid(True, 'minor', color='0.3', linestyle='dotted', linewidth=0.1) yaxis_1.grid(True, 'major', color='0.3', linestyle='solid', linewidth=0.2) yaxis_1.grid(True, 'minor', color='0.3', linestyle='dotted', linewidth=0.1) #================================================================================================================================================== #======= 绘图 #================================================================================================================================================== # 绘制 K 线部分 #================================================================================================================================================== rarray_open = numpy.array(pdata[u'开盘']) rarray_close = numpy.array(pdata[u'收盘']) rarray_high = numpy.array(pdata[u'最高']) rarray_low = numpy.array(pdata[u'最低']) # XXX: 如果 up, down, side 里有一个全部为 False 组成,那么 vlines() 会报错。 if True in up: axes_1.vlines(xindex[up], rarray_low[up], rarray_high[up], color='red', linewidth=0.6, label='_nolegend_') axes_1.vlines(xindex[up], rarray_open[up], rarray_close[up], color='red', linewidth=3.0, label='_nolegend_') if True in down: axes_1.vlines(xindex[down], rarray_low[down], rarray_high[down], color='green', linewidth=0.6, label='_nolegend_') axes_1.vlines(xindex[down], rarray_open[down], rarray_close[down], color='green', linewidth=3.0, label='_nolegend_') if True in side: axes_1.vlines(xindex[side], rarray_low[side], rarray_high[side], color='0.7', linewidth=0.6, label='_nolegend_') axes_1.vlines(xindex[side], rarray_open[side], rarray_close[side], color='0.7', linewidth=3.0, label='_nolegend_') # 绘制均线部分 #================================================================================================================================================== rarray_1dayave = numpy.array(pdata[u'1日权均']) rarray_5dayave = numpy.array(pdata[u'5日均']) rarray_30dayave = numpy.array(pdata[u'30日均']) axes_1.plot(xindex, rarray_1dayave, 'o-', color='white', linewidth=0.1, markersize=0.7, markeredgecolor='white', markeredgewidth=0.1) # 1日加权均线 axes_1.plot(xindex, rarray_5dayave, 'o-', color='yellow', linewidth=0.1, markersize=0.7, markeredgecolor='yellow', markeredgewidth=0.1) # 5日均线 axes_1.plot(xindex, rarray_30dayave, 'o-', color='green', linewidth=0.1, markersize=0.7, markeredgecolor='green', markeredgewidth=0.1) # 30日均线 # 设定 X 轴坐标的范围 #================================================================================================================================================== axes_1.set_xlim(-1, length) # 先设置 label 位置,再将 X 轴上的坐标设为不可见。因为与 成交量子图 共用 X 轴 #================================================================================================================================================== # 设定 X 轴的 Locator 和 Formatter xaxis_1.set_major_locator(xMajorLocator) xaxis_1.set_major_formatter(xMajorFormatter) xaxis_1.set_minor_locator(xMinorLocator) xaxis_1.set_minor_formatter(xMinorFormatter) # 将 X 轴上的坐标设为不可见。 for malab in axes_1.get_xticklabels(minor=False): malab.set_visible(False) for milab in axes_1.get_xticklabels(minor=True): milab.set_visible(False) # 用这一段效果也一样 # pyplot.setp(axes_1.get_xticklabels(minor=False), visible=False) # pyplot.setp(axes_1.get_xticklabels(minor=True), visible=False) # 设定 Y 轴坐标的范围 #================================================================================================================================================== axes_1.set_ylim(ylowlim_price, yhighlim_price) # 设定 Y 轴上的坐标 #================================================================================================================================================== if useexpo: # 主要坐标点 #----------------------------------------------------- yMajorLocator_1 = LogLocator(base=expbase) yMajorFormatter_1 = NullFormatter() # 设定 X 轴的 Locator 和 Formatter yaxis_1.set_major_locator(yMajorLocator_1) yaxis_1.set_major_formatter(yMajorFormatter_1) # 设定 Y 轴主要坐标点与辅助坐标点的样式 # for mal in axes_1.get_yticklabels(minor=False): # mal.set_fontsize(3) # 辅助坐标点 #----------------------------------------------------- minorticks = range(int(ylowlim_price), int(yhighlim_price) + 1, 100) yMinorLocator_1 = FixedLocator(numpy.array(minorticks)) # 确定 Y 轴的 MinorFormatter def y_minor_formatter_1(num, pos=None): return str(num / 100.0) + '0' yMinorFormatter_1 = FuncFormatter(y_minor_formatter_1) # 设定 X 轴的 Locator 和 Formatter yaxis_1.set_minor_locator(yMinorLocator_1) yaxis_1.set_minor_formatter(yMinorFormatter_1) # 设定 Y 轴主要坐标点与辅助坐标点的样式 for mil in axes_1.get_yticklabels(minor=True): mil.set_fontsize(3) else: # 如果使用线性坐标,那么只标主要坐标点 yMajorLocator_1 = MultipleLocator(100) def y_major_formatter_1(num, pos=None): return str(num / 100.0) + '0' yMajorFormatter_1 = FuncFormatter(y_major_formatter_1) # 设定 Y 轴的 Locator 和 Formatter yaxis_1.set_major_locator(yMajorLocator_1) yaxis_1.set_major_formatter(yMajorFormatter_1) # 设定 Y 轴主要坐标点与辅助坐标点的样式 for mal in axes_1.get_yticklabels(minor=False): mal.set_fontsize(3) # 保存图片 #================================================================================================================================================== figobj.savefig(figpath, dpi=figdpi, facecolor=figfacecolor, edgecolor=figedgecolor, linewidth=figlinewidth)
def _make_contour(self, **kwargs): """ method for generalizanting contour and colorbar plotting kwargs cax = matplotlib.Axes used to print colorbar. Default use make_axes_locatable """ Z = self.data.copy() if self.kwargs['vlim'] is not None: vmin, vmax = self.kwargs['vlim'] else: vmin, vmax = [Z.min().min(), Z.max().max()] #np.nanpercentile(Z,[2.5,97.5]) # print vmin, vmax colorbarKwd = {'extend': 'both'} contourKwd = { 'cmap': self.colormap } #'levels':np.linspace(vmin,vmax,100), if self.kwargs['colorbarKind'] == 'Linear': contourKwd['norm'] = Normalize(vmin, vmax) elif self.kwargs['colorbarKind'] == 'Anomaly': contourKwd['norm'] = MidpointNormalize(midpoint=0., vmin=vmin, vmax=vmax) colorbarKwd['format'] = self.kwargs['format'] elif self.kwargs['colorbarKind'] == 'Log': Z.mask(Z <= 0, inplace=True) if self.kwargs['vlim'] is None: vmin, vmax = [Z.min().min(), Z.max().max()] # np.nanpercentile(Z,[1,99]))) # Z[Z < vmin] = vmin # Z[Z > vmax] = vmax contourKwd['norm'] = LogNorm(vmin, vmax) print vmin, vmax minorTicks = np.hstack( [np.arange(1, 10, 1) * log for log in np.logspace(-2, 16, 19)]) minorTicks = minorTicks[(minorTicks >= vmin) & (minorTicks <= vmax)] colorbarKwd.update( dict(format=LogFormatterMathtext(10), ticks=LogLocator(10))) args = (self.x, self.y, Z) cf = self.axes[0].pcolormesh(*args, **contourKwd) # cf = ax.contourf(X,Y,Z,**contourKwd) #extend='both') if 'cax' not in kwargs.keys(): divider = make_axes_locatable(self.axes[0]) cax = divider.append_axes("right", size="3%", pad='1%') else: cax = kwargs['cax'] cbar = plt.colorbar(cf, cax=cax, **colorbarKwd) cbar.set_label(self.kwargs['cbarLabel'], weight='bold') if self.kwargs['colorbarKind'] == 'Log': cbar.ax.yaxis.set_ticks(cf.norm(minorTicks), minor=True) cbar.ax.tick_params(which='minor', width=1, length=4) cbar.ax.tick_params(which='major', width=1, length=6) # ax.yaxis.set_minor_locator(LogLocator(10,subs=np.arange(2,10))) self.kwargs['colorbarKind'] = 'Linear' return cf, cbar