def logz(ax, tix=None): """ Log-scales z-axis, can add tix logarithmically spaced ticks to ax. """ ax.set_zscale('log') if tix: ax.zaxis.set_major_locator(plt.LogLocator(numticks=tix)) ax.zaxis.set_minor_locator( plt.LogLocator(subs=np.arange(2, 10) * .1, numticks=tix))
def property_plot(self, y_t, y_p, y_terr=None, y_perr=None, **kwargs): '''Create plots for dust lum, dust mass and dust temp''' self.setup_default(y_t, y_p, y_terr=y_terr, y_perr=y_perr) self.grid_cells[0].logscale() self.grid_cells[1].logscale() self.task_on_cells('plot') # Set limits and labels xlabels = [ r'True $L_d$ [$L_\odot$]', r'True $M_d$ [$M_\odot$]', r'True $T_d$ [K]' ] if 'limits' in kwargs: limits = kwargs['limits'] else: limits = [[2e4, 2e12], [1e2, 9e8], [7, 42]] for i in range(3): self.grid_cells[i].ax.set_xlabel(xlabels[i]) self.grid_cells[i].set_axislimits(limits[i]) # Extras extras_kwargs = kwargs.get('extras_kwargs', {}) extras_kwargs.setdefault('title', {'fontsize': 18}) self.add_extras(**extras_kwargs) for i in range(2): # log axis self.grid_cells[i].set_axislocator(locator=plt.LogLocator( numticks=5)) self.grid_cells[i].set_axislocator( which='minor', formatter=plt.NullFormatter(), locator=plt.LogLocator(numticks=10)) self.grid_cells[2].set_axislocator(locator=plt.MultipleLocator(10.)) self.grid_cells[2].set_axislocator(which='minor', formatter=plt.NullFormatter(), locator=plt.MultipleLocator(5.)) self.grid_cells[0].ax.set_ylabel('Predicted')
def plot_dist(columns, labels, colors, do_log, include_missing, title): for col, label, color, log in zip(columns, labels, colors, do_log): data = google_tabelog[col] if not include_missing: data = data[data != -1] if log: data = np.log(1 + data) plt.hist(data, density=True, color=color, alpha=0.7, label=label) density = gaussian_kde(dataset=data) density_x = np.linspace(np.amin(data), np.amax(data), 100) density_y = density.evaluate(density_x) plt.plot(density_x, density_y, '--', color=color, alpha=1.0) if log: old_axes = plt.axes() old_axes.xaxis.set_major_locator(plt.LogLocator(base=np.e)) plt.sca(old_axes) dx0, dx1 = np.amin(data), np.amax(data) ticks = np.linspace(dx0, dx1, 5) plt.xticks(ticks=ticks, labels=['{:d}'.format(int(x)) for x in np.exp(ticks)]) plt.title(title) plt.legend() plt.savefig('tmp/{:s}.png'.format(title)) plt.show()
def plot_Welch_Periodogram(self, fmin=40, fmax=2060): PSDW2, fW2 = mlab.psd(self.data, NFFT=4096, Fs=1. / self.dt, window=mlab.window_hanning, noverlap=2048) dfW2 = fW2[1] - fW2[0] cutoff = (fW2 >= fmin) & (fW2 <= fmax) fW2 = fW2[cutoff] PSDW2 = PSDW2[cutoff] print('Maximum power: {}, occured at time period : {} '.format( max(PSDW2), 1. / fW2[np.argmax(PSDW2)])) # plot data fig, ax = plt.subplots(1, 2, figsize=(12, 5)) fig.suptitle('Welch-Method Periodogram') fig.subplots_adjust(bottom=0.12, left=0.07, right=0.95) # plot the raw data ax[0].loglog(fW2, PSDW2, '-') ax[0].set(xlabel='Frequency', ylabel='PSD') ax[0].set_xlim(40, 2060) ax[0].set_ylim(1E-46, 1E-36) ax[0].yaxis.set_major_locator(plt.LogLocator(base=100)) # plot the periodogram ax[1].loglog(1. / fW2, PSDW2, '-') ax[1].set(xlabel='period (days)', ylabel='PSD') return fig, ax
def plot_FFT(self, fmin=40, fmax=2060): # compute PSD using simple FFT N = len(self.data) df = 1. / (N * self.dt) PSD = abs(self.dt * fftpack.fft(self.data)[:(int)(N / 2)])**2 f = df * np.arange(N / 2) cutoff = ((f >= fmin) & (f <= fmax)) f = f[cutoff] PSD = PSD[cutoff] f = f[::100] PSD = PSD[::100] print('Maximum power: {}, occured at time period : {} '.format( max(PSD), 1. / f[np.argmax(PSD)])) fig, ax = plt.subplots(1, 2, figsize=(12, 5)) fig.suptitle('FFT Periodogram') fig.subplots_adjust(bottom=0.12, left=0.07, right=0.95) # plot the raw data ax[0].loglog(f, PSD, '-') ax[0].set(xlabel='Frequency', ylabel='PSD') ax[0].set_xlim(40, 2060) ax[0].set_ylim(1E-46, 1E-36) ax[0].yaxis.set_major_locator(plt.LogLocator(base=100)) # plot the periodogram ax[1].loglog(1. / f, PSD, '-') ax[1].set(xlabel='period (days)', ylabel='PSD') return fig, ax
def plot_all(incl, save=None): global models rows = 2 cols = 2 fig, axes = plt.subplots(nrows=rows, ncols=cols, sharex=True, sharey=True, figsize=(19.20, 10.80)) fig.subplots_adjust(wspace=0., hspace=0.) for i, model in enumerate(models): ax = axes.flatten()[i] star = Star(model, incl) wave_obs, sed_obs = np.loadtxt( '/home/rieutord/Ester/postprocessing/SED/SED', unpack=True) wave_mod, sed_mod = star.SED() ax.loglog(wave_mod * 1e4, sed_mod * 1e-4) ax.loglog(wave_obs, sed_obs, 'o') ax.yaxis.set_minor_locator(plt.LogLocator(base=10, numticks=15)) ax.yaxis.set_minor_formatter(ticker.NullFormatter()) ax.tick_params(labelsize=16, direction='inout', which='both', length=5, width=1) if ax.colNum != 0: ax.tick_params(left=False) else: ax.set_ylabel( 'F$_\lambda$ (erg$\cdot$s$^{-1}\cdot$cm$^{-2}\cdot\mu$m$^{-1}$)', fontsize=20) if ax.rowNum != 1: ax.tick_params(bottom=False) else: ax.set_xlabel('$\lambda$ ($\mu$m)', fontsize=20) text = ( 'M = {star.mod.M/Star.Msun:.2f} M$\odot$\nZ = {star.mod.Z[0, 0]:.3f}\n' 'Xc = {star.mod.Xc:.3f}') props = dict(boxstyle='round', facecolor='white', alpha=0.7) # place a text box in lower left in axes coords ax.text(0.75, 0.90, text, transform=ax.transAxes, verticalalignment='top', bbox=props, fontdict=dict(fontsize=14)) if save: fig.savefig(fname='/home/rieutord/Ester/postprocessing/SED/' + save, bbox_inches='tight') fig.show() return
def plot_one_for_all(incl, save=None, res=False, error=0.1): global models fig, ax = plt.subplots(figsize=(10.80, 10.80)) wave_obs, sed_obs = np.loadtxt( '/home/rieutord/Ester/postprocessing/SED/SED', unpack=True) ax.loglog(wave_obs, sed_obs, 'o') ax.set_xlabel('$\lambda$ ($\mu$m)', fontsize=20) ax.set_ylabel( 'F$_\lambda$ (erg$\cdot$s$^{-1}\cdot$cm$^{-2}\cdot\mu$m$^{-1}$)', fontsize=20) ax.yaxis.set_minor_locator(plt.LogLocator(base=10, numticks=15)) ax.yaxis.set_minor_formatter(ticker.NullFormatter()) ax.tick_params(labelsize=16, direction='inout', which='both', length=5, width=1) linestyles = itertools.cycle([(0, (5, 5)), 'dashdot', (0, (3, 5, 1, 5, 1, 5)), 'dotted', '-']) # Print reduced Chi2 of fit with arbitrary uncertainty on observed data if res: print('Reduced chi2 ({error*100}% artificial error on data):\n') for i, model in enumerate(models): star = Star(mod=model, incl=incl) wave_mod, sed_mod = star.SED() ax.loglog( wave_mod * 1e4, sed_mod * 1e-4, ls=next(linestyles), label= ('M = {star.mod.M/Star.Msun:.2f} M$\odot$, Z = {star.mod.Z[0, 0]:.3f}, ' 'Xc = {star.mod.Xc:.2f}, $\overline{{\mathrm{{T}}}} = ' '{int(star.Teff_mean())} $K'), zorder=0) if res: wave_mod_chi2, sed_mod_chi2 = star.SED(wavelength=wave_obs * 1e-4) sum_squared_res = sum( ((sed_mod_chi2 * 1e-4 - sed_obs) / (error * sed_obs))**2) chi2_red = sum_squared_res / len(sed_mod_chi2) print('model {star.mod.M/Star.Msun:.2f}: {chi2_red}') ax.legend(fontsize=16, loc='lower left') if save: fig.savefig(fname='./' + save, bbox_inches='tight') fig.show() return
def epsPlot(data, size=(6,3)): pos = numpy.arange(len(data))+.5 # the bar centers on the y axis labels = list(data["graph"]) plt.figure(figsize=size) plt.xscale("log") plt.barh(pos, data["edges/s"], align='center', height=0.25, color=green) # notice the 'height' argument plt.yticks(pos, labels) plt.gca().xaxis.set_minor_locator(plt.LogLocator(subs=[0,1,2,3,4,5,6,7,8,9,10])) #gca().xaxis.set_minor_formatter(FormatStrFormatter("%.2f")) plt.xlabel("edges / s") plt.grid(True)
def setup_fig(self): min_xs, max_xs, min_ys, max_ys = zip( *self.xy_range) # list of tuples to tuple of lists Plotter.set_xy_lim(self, min_xs, max_xs, min_ys, max_ys) if (min(min_ys) > 1.0e-2): subsyy = [2, 3, 4, 5, 7] else: subsyy = [] plt.yscale('log', subsy=subsyy, figure=self.fig) plt.gca().yaxis.set_major_locator(plt.LogLocator(numticks=7)) plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0)) plt.tick_params(axis='x', which='major', labelsize=20) Plotter.setup_fig(self)
def plot(model, incl, save=None): global directory # Check that model exists in the right directory try: assert os.path.exists(model) except AssertionError: print("attention file not found") #raise FileNotFoundError(f"No such file in directory /{directory} : {model}") # Create the stellar visible grid star = Star(mod=model, incl=incl) # Get observed SED wave_obs, sed_obs = np.loadtxt( '/home/rieutord/Ester/postprocessing/SED/SED', unpack=True) #skiprows=1, unpack=True) # compute theoretical SED wave_mod, sed_mod = star.SED() # Plot theoretical SED of model (line) alongside observed SED (points) fig, ax = plt.subplots(figsize=(19.20, 10.80)) ax.loglog(wave_mod * 1e4, sed_mod * 1e-4) ax.loglog(wave_obs, sed_obs, 'o') fig.suptitle('SED', fontsize=24) ax.set_title('M = {:.5g} Msun, Z = {:.3f}, Xc = {:.5g}, i = {:.2f}'.format( star.mod.M / Star.Msun, star.mod.Z[0, 0], star.mod.Xc, star.incl), fontsize=18) ax.set_xlabel('$\lambda$ ($\mu$m)', fontsize=20) ax.set_ylabel( 'F$_\lambda$ (erg$\cdot$s$^{-1}\cdot$cm$^{-2}\cdot\mu$m$^{-1}$)', fontsize=20) ax.yaxis.set_minor_locator(plt.LogLocator(base=10, numticks=15)) ax.yaxis.set_minor_formatter(ticker.NullFormatter()) ax.tick_params(labelsize=16, direction='inout', which='both', length=5, width=1) # Save figure (filename must be given as save='filename' in function arguments) if save: fig.savefig(fname='/home/rieutord/Ester/postprocessing/SED/' + save, bbox_inches='tight') fig.show() return
def setup_fig(self): plt.ylim(self.min_y, 1) if (self.min_y > 1.0e-2): subsyy = [2, 3, 4, 5, 7] else: subsyy = [] plt.yscale('log', subsy=subsyy, figure=self.fig) if (self.min_y > 1.0e-2): plt.tick_params(axis='y', which='minor', labelsize=14) plt.gca().yaxis.set_minor_formatter(FuncFormatter(format_label)) else: plt.gca().yaxis.set_major_locator(plt.LogLocator(numticks=7)) plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0)) plt.tick_params(axis='x', which='major', labelsize=20) Plotter.setup_fig(self)
def timePlot(data, size=(6, 3)): if not have_plt: raise MissingDependencyError("matplotlib") pos = numpy.arange(len(data)) + .5 # the bar centers on the y axis labels = list(data["graph"]) plt.figure(figsize=size) plt.xscale("symlog") plt.barh(pos, data["time"], align='center', height=0.25, color=lightred) # notice the 'height' argument plt.yticks(pos, labels) plt.gca().xaxis.set_minor_locator( plt.LogLocator(subs=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) #gca().xaxis.set_minor_formatter(FormatStrFormatter("%.2f")) plt.xlabel("time [s]") plt.grid(True)
def setup_fig(self): min_xs, max_xs, min_ys, max_ys = zip( *self.xy_range) # list of tuples to tuple of lists Plotter.set_xy_lim(self, min_xs, max_xs, min_ys, max_ys) plt.ylim(min(min_ys), max(max_ys)) plt.yscale('linear', figure=self.fig) plt.xscale('log', figure=self.fig) plt.gca().xaxis.set_major_locator(plt.LogLocator(numticks=7)) plt.xlim(min(min_xs), max(max_xs)) summary = "\n".join(self.summary) plt.annotate(summary, (0, 0), (0, -20), xycoords='axes fraction', textcoords='offset points', va='top') plt.subplots_adjust(bottom=0.15) Plotter.setup_fig(self)
def setup_fig(self): min_xs, max_xs, min_ys, max_ys = zip( *self.xy_range) # list of tuples to tuple of lists Plotter.set_xy_lim(self, min_xs, max_xs, min_ys, max_ys) if (min(min_ys) > 1.0e-2): subsyy = [2, 3, 4, 5, 7] else: subsyy = [] plt.yscale('log', subsy=subsyy, figure=self.fig) plt.gca().yaxis.set_major_locator(plt.LogLocator(numticks=7)) plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0)) plt.tick_params(axis='x', which='major', labelsize=20) ##add xy label and adjust the margin accordingly #plt.xlabel('number of $O(n)$ operations', fontsize=20) #plt.ylabel('$(f-f^*)/f*$', fontsize=20) #plt.subplots_adjust(bottom=0.13,left=0.133) Plotter.setup_fig(self)
def contour(ax, X, Y, Z, fill=True, contour_levels=10, line_levels=5, line_color='k', **kwargs): """ Draw contour lines or filled contours. :param ax: Which axes to use for the plot. :param array X, Y: The coordinates of the values in Z. X and Y must both be 2-D with the same shape as Z (e.g. created via :py:func:`numpy.meshgrid`) :param array Z: 2D data to plot. :param bool fill: draw contour lines or filled contours :param contour_levels: if fill is True; contour_levels determines the number of the filled contours. :param line_levels: if fill is True; line_levels determines the number of the lines. :param line_color: if fill is True; line_color determines the color of the lines. :param kwargs: Unknown keyword arguments are passed to :py:func:`ax.contour()` or :py:func:`ax.contourf()`. :return: image object >>> im = imshow(ax, X, Y, Z) Only draw contour lines. >>> im = contour(ax, x, y, Z, fill=True) Draw contour lines and filled contours, >>> im = contour(ax, x, y, Z, fill=True, contour_levels=10, line_levels=5) Draw contour lines and filled contours, filled levels determined by contour_levels and line number determined by line_levels >>> im = contour(ax, x, y, Z, fill=True, line_color='r') line color determined by line_color >>> im = contour(ax, x, y, Z, fill=True, cmap=plt.cm.bone) filled color determined by cmap >>> im = contour(ax, X, Y, Z, fill=True, alpha=0.5) The alpha blending value, between 0 (transparent) and 1 (opaque). >>> Zm = np.ma.masked_where(np.abs(Z) < 0.000001, Z) >>> im = contour(ax, x, y, Zm, fill=False) control the masked region. >>> from matplotlib import ticker >>> im = contour(ax, x, y, Z, locator=ticker.LogLocator(), fill=True) log locator tells contourf to use a log scale """ assert X.shape == Z.shape and Y.shape == Z.shape, "The coordinates of X and Y must have the same shape as Z" if fill: line_factor = int(contour_levels)//int(line_levels) im = ax.contourf(X, Y, Z, levels=contour_levels, **kwargs) ax.contour(im, levels=im.levels[::line_factor], colors=line_color) else: im = ax.contour(X, Y, Z, locator=plt.LogLocator(), **kwargs) fmt = ticker.LogFormatterMathtext() ax.clabel(im, im.levels, fmt=fmt) return im
def plot_funct_with_Theta(a, b, x_size, y_size, theta): x_ax = np.linspace(-x_size,x_size); y_ax = np.linspace(-y_size,y_size); X,Y = np.meshgrid(x_ax,y_ax); himmelblau_fkt = (X**2 + Y -11)**2 + (X + Y**2 - 7)**2; fig, ax = plt.subplots(); cs = ax.contour(X,Y,himmelblau_fkt, locator=plt.LogLocator()); fmt = ticker.LogFormatterMathtext(); fmt.create_dummy_axis(); ax.clabel(cs, cs.levels, fmt=fmt); ax.set_title("Bananafunction Min at [1,1]"); for a in range(theta[0].size - 1): #Plot all thetas inclusive the intermidiate results if(theta[0][a] != 0 or theta[1][a] != 0): #Only plot calculated values (instance created via np.zeros and probability for (0,0) is near zero...) plt.plot(theta[0][a],theta[1][a],'ro'); #minima=[1 1]; plt.plot(1,1,'rx'); plt.show();
def plot_SED(self): wave, sed = self.SED() fig, ax = plt.subplots(figsize=(19.20, 10.80)) ax.loglog(wave * 1e4, sed * 1e-4) ax.set_title('SED') ax.tick_params(labelsize=16, direction='inout', which='both', length=5, width=1) ax.set_xlabel('$\lambda$ ($\mu$m)', fontsize=20) ax.set_ylabel( 'F$_\lambda$ (erg$\cdot$s$^{-1}\cdot$cm$^{-2}\cdot\mu$m$^{-1}$)', fontsize=20) ax.yaxis.set_minor_locator(plt.LogLocator(base=10, numticks=15)) ax.yaxis.set_minor_formatter(ticker.NullFormatter()) fig.show() return
width = 10 else: width = 12 f, ax = plt.subplots(figsize=(width, 7)) sns.set_style("dark") sns.set(font_scale=1.15) p = sns.scatterplot(x=x, y=y, ax=ax) ax.set(xscale='log', yscale='linear') # format axis labels formatter = FuncFormatter(lambda x, _: '{:,.16g}m'.format(x) ) # https://stackoverflow.com/a/49306588/3904031 ax.xaxis.set_major_formatter(formatter) ax.xaxis.set_major_locator(plt.LogLocator(base=10, subs=(1.0, 0.5))) formatter = FuncFormatter(lambda y, _: '{:,.16g}'.format(10**y) ) # https://stackoverflow.com/a/49306588/3904031 ax.yaxis.set_major_formatter(formatter) ax.yaxis.set_major_locator(plt.FixedLocator([1, 2])) # create legend with a color sample for each region texts = [ plt.text(x[i], y[i], lab[i], ha='center', va='bottom', color=color[reg[i]]) for i in range(len(lab)) ] # R-squared without regions
def performance_scaling(data: pd.DataFrame, set_axes_limits: bool=True, plot_regression: bool=True) -> (plt.Figure, plt.Axes): """ Parameters ---------- data : pd.DataFrame with 6 columns: "year", "performance", "kind" ∈ ["compute", "memory", "interconnect"], "name" (label shown in the plot, it can be empty), "base" (base value used for speedup, it can be empty), "comment" (e.g. data source or non-used label, it can be empty). Returns ------- fig : matplotlib figure containing the plot ax : matplotlib axis containing the plot """ ############## # Plot setup # ############## # Reset matplotlib settings; plt.rcdefaults() # Setup general plotting settings; sns.set_style("white", {"ytick.left": True, "xtick.bottom": True}) plt.rcParams["font.family"] = ["Latin Modern Roman Demi"] plt.rcParams['axes.labelpad'] = 0 # Padding between axis and axis label; plt.rcParams['xtick.major.pad'] = 1 # Padding between axis ticks and tick labels; plt.rcParams['ytick.major.pad'] = 1 # Padding between axis ticks and tick labels; plt.rcParams['axes.linewidth'] = 0.8 # Line width of the axis borders; # Create a figure for the plot, and adjust margins; fig = plt.figure(figsize=(6, 2.5)) gs = gridspec.GridSpec(1, 1) plt.subplots_adjust(top=0.98, bottom=0.1, left=0.12, right=0.99) ax = fig.add_subplot(gs[0, 0]) # Set axes limits; if set_axes_limits: ax.set_xlim(X_LIMITS) ax.set_ylim(Y_LIMITS) ################# # Main plot ##### ################# # Measure performance increase over 20 and 2 years; kind_increase = {} # Add a scatterplot for individual elements of the dataset, and change color based on hardware type; ax = sns.scatterplot(x="year", y="performance", hue="kind", style="kind", palette=PALETTE, markers=MARKERS, s=15, data=data, ax=ax, edgecolor="#2f2f2f", linewidth=0.5, zorder=4) # Add a regression plot to highlight the correlation between variables, with 95% confidence intervals; if plot_regression: for i, (kind, g) in enumerate(data.groupby("kind", sort=False)): data_tmp = g.copy() # We fit a straight line on the log of the relative performance, as the scaling is exponential. # Then, the real prediction is 10**prediction; regr = linear_model.LinearRegression() regr.fit(data_tmp["year"].values.reshape(-1, 1), np.log10(data_tmp["performance"].values.reshape(-1, 1))) data_tmp["prediction"] = np.power(10, regr.predict(data_tmp["year"].values.astype(float).reshape(-1, 1))) ax = sns.lineplot(x=[data_tmp["year"].iloc[0], data_tmp["year"].iloc[-1]], y=[data_tmp["prediction"].iloc[0], data_tmp["prediction"].iloc[-1]], color=PALETTE[i], ax=ax, alpha=0.5, linewidth=6) # Use the regression line to obtain the slope over 2 and 10 years; slope = (np.log10(data_tmp["prediction"].iloc[-1]) - np.log10(data_tmp["prediction"].iloc[0])) / ((data_tmp["year"].iloc[-1] - data_tmp["year"].iloc[0]).days / 365) slope_2_years = 10**(slope * 2) slope_20_years = 10**(slope * 20) kind_increase[kind] = (slope_2_years, slope_20_years) ax.legend_.remove() # Hack to remove legend; ##################### # Add labels ######## ##################### # Associate a color to each kind of hardware (compute, memory, interconnection) def get_color(c): # Make the color darker, to use it for text; hue, saturation, brightness = colors.rgb_to_hsv(colors.to_rgb(c)) return sns.set_hls_values(c, l=brightness * 0.6, s=saturation * 0.7) kind_to_col = {k: get_color(PALETTE[i]) for i, k in enumerate(data["kind"].unique())} data["name"] = data["name"].fillna("") for i, row in data.iterrows(): label = row["name"] # Label-specific adjustments; if label: if label == "Pentium II Xeon": xytext = (5, -9) elif label == "PCIe 4.0": xytext = (5, -9) elif label == "Radeon Fiji": xytext = (-7, 5) elif label == "TPUv2": xytext = (-7, 5) elif row["kind"] == "interconnect": xytext = (0, -9) else: xytext = (0, 5) ax.annotate(label, xy=(row["year"], row["performance"]), size=7, xytext=xytext, textcoords="offset points", ha="center", color=kind_to_col[row["kind"]]) ##################### # Style fine-tuning # ##################### # Log-scale y-axis; plt.yscale("log") # Turn on the grid; ax.yaxis.grid(True, linewidth=0.3) ax.xaxis.grid(True, linewidth=0.3) # Set tick number and parameters on x and y axes; def year_formatter(x, pos=None): d = num2date(x) if (d.year - X_LIMITS[0].year) % 3 != 0: return "" else: return d.year ax.xaxis.set_major_locator(YearLocator()) ax.xaxis.set_minor_locator(MonthLocator(interval=3)) ax.xaxis.set_major_formatter(FuncFormatter(year_formatter)) ax.yaxis.set_major_locator(plt.LogLocator(base=10, numticks=15)) ax.tick_params(axis="x", direction="out", which="both", bottom=True, top=False, labelsize=7, width=0.5, size=5) ax.tick_params(axis="x", direction="out", which="minor", size=2) # Update size of minor ticks; ax.tick_params(axis="y", direction="out", which="both", left=True, right=False, labelsize=7, width=0.5, size=5) ax.tick_params(axis="y", direction="out", which="minor", size=2) # Update size of minor ticks; # Ticks, showing relative performance; def format_speedup(l): if l >= 1: return str(int(l)) else: return f"{l:.1f}" ax.set_yticklabels(labels=[format_speedup(l) + r"$\mathdefault{\times}$" for l in ax.get_yticks()], ha="right", fontsize=7) # Add a fake legend with summary data. # We don't use a real legend as we need rows with different colors and we don't want patches on the left. # Also, we want the text to look justified. def get_kind_label(k): kind_name = "" if k == "compute": kind_name = "HW FLOPS" elif k == "memory": kind_name = "DRAM BW" else: kind_name = "Interconnect BW" return kind_name # Create a rectangle used as background; rectangle = {"boxstyle": "round", "facecolor": "white", "alpha": 0.8, "edgecolor": "#B8B8B8", "linewidth": 0.5, "pad": 0.5} for i, (k, v) in enumerate(kind_increase.items()): pad = " " * 48 + "\n\n" # Add padding to first label, to create a large rectangle that covers other labels; # Use two annotations, to make the text look justified; ax.annotate(get_kind_label(k) + ":" + (pad if i == 0 else ""), xy=(0.023, 0.94 - 0.05 * i), xycoords="axes fraction", fontsize=7, color=kind_to_col[k], ha="left", va="top", bbox=rectangle if i == 0 else None) ax.annotate(f"{v[1]:.0f}" + r"$\mathdefault{\times}$" + f"/20 years ({v[0]:.1f}" + r"$\mathdefault{\times}$"+ "/2 years)", xy=(0.43, 0.941 - 0.05 * i), xycoords="axes fraction", fontsize=7, color=kind_to_col[k], ha="right", va="top") # Add axes labels; plt.ylabel("Performance Scaling", fontsize=8) plt.xlabel(None) return fig, ax
ad, "density", "temperature", [ "cell_mass", ], weight_field=None, ) # Ensure the axes and colorbar limits match for all plots p.set_xlim(1.0e-32, 8.0e-26) p.set_ylim(1.0e1, 2.0e7) p.set_zlim(("gas", "cell_mass"), 1e42, 1e46) # This forces the ProjectionPlot to redraw itself on the AxesGrid axes. plot = p.plots[("gas", "cell_mass")] plot.figure = fig plot.axes = grid[i].axes if i == 0: plot.cax = grid.cbar_axes[i] # Actually redraws the plot. p._setup_plots() # Modify the axes properties **after** p._setup_plots() so that they # are not overwritten. plot.axes.xaxis.set_minor_locator( plt.LogLocator(base=10.0, subs=[2.0, 5.0, 8.0])) plt.savefig("multiplot_phaseplot.png")
print " L(M = Gauss) = %.2e +/- %.2e" % (I_gauss, err_gauss) print " O_{CG} = %.3g +/- %.3g" % (O_CG, err_O_CG) #------------------------------------------------------------ # calculate the results as a function of number of points Nrange = np.arange(10, 101, 2) Odds = np.zeros(Nrange.shape) for i, N in enumerate(Nrange): res = calculate_odds_ratio(xi[:N]) Odds[i] = res[2][0] #------------------------------------------------------------ # plot the results fig = plt.figure(figsize=(5, 3.75)) fig.subplots_adjust(hspace=0.1) ax1 = fig.add_subplot(211, yscale='log') ax1.plot(Nrange, Odds, '-k') ax1.set_ylabel(r'$O_{CG}$ for $N$ points') ax1.set_xlim(0, 100) ax1.xaxis.set_major_formatter(plt.NullFormatter()) ax1.yaxis.set_major_locator(plt.LogLocator(base=10000.0)) ax2 = fig.add_subplot(212) ax2.scatter(np.arange(1, len(xi) + 1), xi, lw=0, s=16, c='k') ax2.set_xlim(0, 100) ax2.set_xlabel('Sample Size $N$') ax2.set_ylabel('Sample Value') plt.show()
fmt = '%r %%' plt.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10) ################################################## # Label contours with arbitrary strings using a # dictionary plt.figure() # Basic contour plot CS = plt.contour(X, Y, Z) fmt = {} strs = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh'] for l, s in zip(CS.levels, strs): fmt[l] = s # Label every other level using strings plt.clabel(CS, CS.levels[::2], inline=True, fmt=fmt, fontsize=10) # Use a Formatter plt.figure() CS = plt.contour(X, Y, 100**Z, locator=plt.LogLocator()) fmt = ticker.LogFormatterMathtext() fmt.create_dummy_axis() plt.clabel(CS, CS.levels, fmt=fmt) plt.title("$100^Z$") plt.show()
ax.set_ylabel('flux') ax.set_xlim(-5, 105) # Second panel: the periodogram & significance levels ax1 = fig.add_subplot(212, xscale='log') ax1.plot(period, PS, '-', c='black', lw=1, zorder=1) ax1.plot([period[0], period[-1]], [sig1, sig1], ':', c='black') ax1.plot([period[0], period[-1]], [sig5, sig5], ':', c='black') ax1.annotate("", (0.3, 0.65), (0.3, 0.85), ha='center', arrowprops=dict(arrowstyle='->')) ax1.set_xlim(period[0], period[-1]) ax1.set_ylim(-0.05, 0.85) ax1.set_xlabel(r'period (days)') ax1.set_ylabel('power') # Twin axis: label BIC on the right side ax2 = ax1.twinx() ax2.set_ylim(tuple(lomb_scargle_BIC(ax1.get_ylim(), y_obs, dy))) ax2.set_ylabel(r'$\Delta BIC$') ax1.xaxis.set_major_formatter(plt.FormatStrFormatter('%.1f')) ax1.xaxis.set_minor_formatter(plt.FormatStrFormatter('%.1f')) ax1.xaxis.set_major_locator(plt.LogLocator(10)) ax1.xaxis.set_major_formatter(plt.FormatStrFormatter('%.3g')) plt.show()
rasterized=True, vmin=v_cbar_min, vmax=v_cbar_max) fmt = ticker.LogFormatterSciNotation() fmt.create_dummy_axis() if args.density_threshold != 0.0: exp_min = np.log10(image_dict['density_threshold']) else: exp_min = np.log10(cbar_min) exp_max = np.log10(cbar_max) n_level = (exp_max - exp_min) * 2 + 1 contour_levels = np.logspace(exp_min, exp_max, int(n_level)) CS = ax.contour(X, Y, image, locator=plt.LogLocator(), linewidths=0.5, colors='k', levels=contour_levels) #'{:.1e}'.format(your_num) def func(x): s = "%.0g" % x if "e" in s: tup = s.split('e') significand = tup[0].rstrip('0').rstrip('.') sign = tup[1][0].replace('+', '') exponent = tup[1][1:].lstrip('0') s = ('%se%s%s' % (significand, sign, exponent)).rstrip('e') return s
label = 'valori ottenuti dalla serie (5 A)') plt.errorbar(iteration, abs(l3 - I3), c = 'b', ls = '-', marker = 'X', label = 'valori ottenuti dalla serie (7 A)') plt.grid(c = "gray") plt.grid(b=True, which='major', c='#666666', ls='--') plt.grid(b=True, which='minor', c='#999999', ls='--', alpha=0.2) plt.minorticks_on() plt.yscale('log') ax=plt.gca() ax.tick_params(direction='in', length=5, width=1., top=True, right=True) ax.tick_params(which='minor', direction='in', width=1., top=True, right=True) if tick: ax.xaxis.set_major_locator(plt.MultipleLocator(2)) ax.xaxis.set_minor_locator(plt.MultipleLocator(1)) ax.yaxis.set_major_locator(plt.LogLocator(numticks=16)) ax.yaxis.set_minor_locator(plt.LogLocator(subs=np.arange(2, 10)*.1, numticks = 16)) ax.xaxis.set_minor_formatter(plt.NullFormatter()) plt.tight_layout() legend = plt.legend(loc='upper right', shadow=True) fig3 = plt.figure(3) gridsize = (1, 1./3) plt.title("Convergenza a $v$ col metodo di Newton", size = 12) plt.xlabel("Grado di iterazione", size = 11, x = 0.8) plt.ylabel("$x - v$ [V]", size = 11) voltage1 = ddp(I1) voltage2 = ddp(I2) voltage3 = ddp(I3) variable1 = voltage1 - I1*R
v_std = np.std(vel_rad/100000) v_cbar_min = -1 v_cbar_max = 1 plot = ax.pcolormesh(X, Y, vel_rad/100000, cmap='idl06_r', rasterized=True, vmin=v_cbar_min, vmax=v_cbar_max) fmt = ticker.LogFormatterSciNotation() fmt.create_dummy_axis() if args.density_threshold != 0.0: exp_min = np.log10(args.density_threshold) else: exp_min = np.log10(cbar_min) exp_max = np.log10(cbar_max) n_level = (exp_max-exp_min)*2 + 1 contour_levels = np.logspace(exp_min, exp_max, int(n_level)) CS = ax.contour(X,Y,image, locator=plt.LogLocator(), linewidths=0.5, colors='k', levels=contour_levels) #'{:.1e}'.format(your_num) def func(x): s = "%.0g" % x if "e" in s: tup = s.split('e') significand = tup[0].rstrip('0').rstrip('.') sign = tup[1][0].replace('+', '') exponent = tup[1][1:].lstrip('0') s = ('%se%s%s' % (significand, sign, exponent)).rstrip('e') return s #ax.clabel(CS,CS.levels,fmt=func) plt.gca().set_aspect('equal') cbar = plt.colorbar(plot, pad=0.0)
def plot_scatter(columns, labels, title, log): filter_col0 = google_tabelog[columns[0]] != -1 filter_col1 = google_tabelog[columns[1]] != -1 data = google_tabelog[filter_col0 & filter_col1] x = np.log(1+data[columns[0]]) if log[0] else data[columns[0]] y = np.log(1+data[columns[1]]) if log[1] else data[columns[1]] # Scatterplot if columns[2]: filter_col2 = google_tabelog[columns[2]] != -1 data = data[filter_col2] x = np.log(1 + data[columns[0]]) if log[0] else data[columns[0]] y = np.log(1 + data[columns[1]]) if log[1] else data[columns[1]] c = np.log(1+data[columns[2]]) if log[2] else data[columns[2]] bin_edges = np.histogram_bin_edges(np.unique(c), bins=5) c_bin_idx = np.digitize(c, bin_edges, right=False) c_binned = np.array([bin_edges[i if i < len(bin_edges) else i-1] for i in c_bin_idx]) cmap = get_cmap('rainbow') normalizer = Normalize(vmin=bin_edges[0], vmax=bin_edges[-1]) path = plt.scatter(x, y, s=5, alpha=0.5, c=c_binned, cmap=cmap, norm=normalizer, zorder=10) axes = path.axes x0, x1, y0, y1 = axes.viewLim.x0, axes.viewLim.x1, axes.viewLim.y0, axes.viewLim.y1 legend_elements = [Line2D([0], [0], marker='.', markersize=5, linestyle='', color=cmap(normalizer(bin_edges[i+1])), label='{0:.1f}~{1:.1f}'.format(np.exp(bin_edges[i]) if log[2] else bin_edges[i], np.exp(bin_edges[i+1]) if log[2] else bin_edges[i+1]) ) for i in range(len(bin_edges)-1)] plt.legend(handles=legend_elements, title=labels[2], loc=(0.655, 0.11)) else: lines = plt.plot(x, y, color="#404040", marker='.', markersize=5, linestyle='', alpha=0.5, zorder=10) axes = lines[0].axes x0, x1, y0, y1 = axes.viewLim.x0, axes.viewLim.x1, axes.viewLim.y0, axes.viewLim.y1 # Linear Regression slope, intercept, r_value, p_value, std_err = linregress(x, y) r_value *= r_value print("Slope: {:.2f} Intercept: {:.2f} R2: {:.4f} p-value: {:.4f}, Std Err: {:.2f}".format( slope, intercept, r_value, p_value, std_err )) plt.plot(x, intercept + x * slope, color='#2c7bb6', alpha=1.0, linestyle='-', linewidth=2, label='fitted line', zorder=11) if log[0] and log[1]: lingress_text = r'$\log y={a:.2f} \log x{b}{c:.2f}$'.format(a=slope, b='+' if intercept >= 0.0 else '-', c=np.abs(intercept)) elif log[0] and not log[1]: lingress_text = r'$y={a:.2f}\log x{b}{c:.2f}$'.format(a=slope, b='+' if intercept >= 0.0 else '-', c=np.abs(intercept)) elif not log[0] and log[1]: lingress_text = r'$\log y={a:.2f}x{b}{c:.2f}$'.format(a=slope, b='+' if intercept >= 0.0 else '-', c=np.abs(intercept)) else: lingress_text = r'$y={a:.2f}x{b}{c:.2f}$'.format(a=slope, b='+' if intercept >= 0.0 else '-', c=np.abs(intercept)) plt.text(x=x0 + (x1 - x0) * 0.65, y=y1, s=lingress_text) lingress_text = r'$R^{{2}}={d:.2f}, p={e:.4f}$'.format(d=r_value, e=p_value) plt.text(x=x0 + (x1 - x0) * 0.65, y=y1 - (y1 - y0) * 0.048, s=lingress_text) lingress_text = r'$\epsilon^{{2}}={f:.3f}$'.format(f=std_err) plt.text(x=x0 + (x1 - x0) * 0.65, y=y1 - (y1 - y0) * 0.048 * 2, s=lingress_text) # x-hist hist_height = (y1 - y0) * 0.2 density = gaussian_kde(dataset=x) density_x = np.linspace(x0, x1) density_y = density.evaluate(density_x) density_y = (density_y / np.amax(density_y)) * hist_height + y0 plt.plot(density_x, density_y, '--', color='#1a9641', alpha=0.7, zorder=9) plt.fill_between(x=density_x, y1=density_y, y2=y0, color='#1a9641', alpha=0.3, zorder=9) # y-hist hist_height = (x1 - x0) * 0.2 density = gaussian_kde(dataset=y) density_x = np.linspace(y0, y1) density_y = density.evaluate(density_x) density_y = (density_y / np.amax(density_y)) * hist_height + x0 plt.plot(density_y, density_x, '--', color='#d7191c', alpha=0.7, zorder=9) plt.fill_betweenx(y=density_x, x1=density_y, x2=x0, color='#d7191c', alpha=0.3, zorder=9) plt.xlabel(labels[0]) plt.ylabel(labels[1]) plt.title(title) if log[0]: old_axes = plt.axes() old_axes.xaxis.set_major_locator(plt.LogLocator(base=np.e)) plt.sca(old_axes) dx0, dx1 = axes.dataLim.x0, axes.dataLim.x1 ticks = np.linspace(dx0, dx1, 5) plt.xticks(ticks=ticks, labels=['{:d}'.format(int(x)) for x in np.exp(ticks)]) if log[1]: old_axes = plt.axes() old_axes.yaxis.set_major_locator(plt.LogLocator(base=np.e)) plt.sca(old_axes) dy0, dy1 = axes.dataLim.y0, axes.dataLim.y1 ticks = np.linspace(dy0, dy1, 5) plt.yticks(ticks=ticks, labels=['{:d}'.format(int(x)) for x in np.exp(ticks)]) plt.savefig('tmp/{:s}.png'.format(title)) plt.show()
ax = plt.axes(xscale='log', yscale='log') # only plot every 1000th; plotting all 1E6 takes too long ax.plot(p_sorted[::1000], np.linspace(0, 1, 1000), '-k') ax.plot(p_sorted[::1000], p_sorted[::1000], ':k', lw=1) # plot the cutoffs for various values of expsilon p_reg_over_eps = 10**np.linspace(-3, 0, 100) for (i, epsilon) in enumerate([0.1, 0.01, 0.001, 0.0001]): x = p_reg_over_eps * epsilon y = p_reg_over_eps ax.plot(x, y, '--k') ax.text(x[1], y[1], r'$\epsilon = %.1g$' % epsilon, ha='center', va='bottom', fontsize=16, rotation=70) ax.xaxis.set_major_locator(plt.LogLocator(base=100)) ax.set_xlim(1E-12, 1) ax.set_ylim(1E-3, 1) ax.set_xlabel('$p = 1 - H_B(i)$') ax.set_ylabel('normalized $C(p)$') plt.show()
CS1 = ax1.contour(X, Y, Z) fmt = {} strs = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh'] for l, s in zip(CS1.levels, strs): fmt[l] = s # Label every other level using strings ax1.clabel(CS1, CS1.levels[::2], inline=True, fmt=fmt, fontsize=10) ############################################################################### # Use a Formatter fig2, ax2 = plt.subplots() CS2 = ax2.contour(X, Y, 100**Z, locator=plt.LogLocator()) fmt = ticker.LogFormatterMathtext() fmt.create_dummy_axis() ax2.clabel(CS2, CS2.levels, fmt=fmt) ax2.set_title("$100^Z$") plt.show() ############################################################################# # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.axes.Axes.contour` / `matplotlib.pyplot.contour`
def main(): start_time = time.time() ## Generate model graph ## if args.graph == 'er': # Erdős-Rényi model, Random graph n = 5000 # node p = 0.04 # probability of edge generation seed = 1234 print(f'Graph type: Erdős-Rényi model\n' f'# n: {n}\n' f'# p: {p}\n' f'# seed: {seed}\n' f'Generating graph...') G = nx.fast_gnp_random_graph(n=n, p=p, seed=seed, directed=False) elif args.graph == 'ws': # Watts–Strogatz model, Small-world graph n = 5000 # node k = 20 # the number of neighbor node to connect with respect to every node p = 0.01 # re-wiring probability. Generate random graph when p=1. seed = 1234 print(f'Graph type: Watts–Strogatz model\n' f'# n: {n}\n' f'# k: {k}\n' f'# p: {p}\n' f'# seed: {seed}\n' f'Generating graph...') G = nx.watts_strogatz_graph(n=n, k=k, p=p, seed=seed) elif args.graph == 'ba': # Barabási–Albert model, Scale-free graph n = 5000 # node m = 10 # the number of new edge to wire with the existing nodes seed = 1234 print(f'Graph type: Barabási–Albert model\n' f'# n: {n}\n' f'# m: {m}\n' f'# seed: {seed}\n' f'Generating graph...') G = nx.barabasi_albert_graph(n=n, m=m, seed=seed) else: print('[ERROR] You need to select model graph.') ## Show graph summary ## print( f"-- graph summary --\n" f"# nodes: {nx.number_of_nodes(G)}\n" f"# edges: {nx.number_of_edges(G)}\n" f"# connected components: {nx.number_connected_components(G)}\n" f"# average shortest path: {nx.average_shortest_path_length(G)}\n" f"# average clustering coefficient: {nx.average_clustering(G)}\n" f"# degree assortativity coefficient: {nx.degree_assortativity_coefficient(G)}\n" f"# graph diameter: {nx.diameter(G)}\n" f"# graph density: {nx.density(G)}") ## Calculate average degree ## deg = [] for k, l in G.degree(): # {node: degree, ...} deg.append(l) average_degree = sum(deg) / len(deg) print(f'# average degree: {average_degree}') ## Export generated graph as tsv file ## edge_type = "interaction" # Tentative edge type name with open(args.output, "w") as fp: for e in G.edges(): fp.write(str(e[0]) + "\t" + edge_type + "\t" + str(e[1]) + "\n") print(f'[SAVE] graph file: {args.output}') ## Calculate degree distribution probability ## pmf = ts.Pmf(deg) # {degree: probability, ...} # print(f'pmf mean: {pmf.Mean()}, pmf std: {pmf.Std()}') pmf_degree = [] # degree pmf_prob = [] # degree distribution probability for i in pmf: pmf_degree.append(i) pmf_prob.append(pmf[i]) ## power law fitting using mudule ## print(f'--- power law fitting parameter ---') np.seterr(divide='ignore', invalid='ignore') # a magical spell fit = powerlaw.Fit( deg, discrete=True) # fitting degree distribution probability to linear R, p = fit.distribution_compare('power_law', 'exponential') print(f'# power law gamma: {fit.power_law.alpha}\n' f'# gammma standard error(std): {fit.power_law.sigma}\n' f'# fix x min: {fit.fixed_xmin}\n' f'# discrete: {fit.discrete}\n' f'# x min: {fit.xmin}\n' f'# loglikelihood ratio: {R}\n' f'# significant value: {p}') ## Plot degree distbibution probability (normal scale) ## fig = plt.figure(figsize=(8, 6), tight_layout=True) ax = fig.add_subplot(1, 1, 1) ax.spines['top'].set_linewidth(1) ax.spines['bottom'].set_linewidth(1) ax.spines['left'].set_linewidth(1) ax.spines['right'].set_linewidth(1) ax.scatter(pmf_degree, pmf_prob, c='black', s=30, alpha=1, linewidths=0) ax.tick_params(direction='out', which='major', axis='both', length=4, width=1, labelsize=20, pad=10) ax.set_xlabel('k', fontsize=25, labelpad=10) ax.set_ylabel('P(k)', fontsize=25, labelpad=10) deg_fig_name = args.fig + '_degdist_plot.pdf' plt.savefig(deg_fig_name, dpi=300, format='pdf', transparent=True) plt.clf() print(f'[SAVE] degree distribution figure: {deg_fig_name}') ## Plot degree distbibution probability (log scale) ## fig = plt.figure(figsize=(6, 6), tight_layout=True) ax = fig.add_subplot(1, 1, 1) ax.spines['top'].set_linewidth(1) ax.spines['bottom'].set_linewidth(1) ax.spines['left'].set_linewidth(1) ax.spines['right'].set_linewidth(1) ax.set_xscale('log', base=10) ax.set_yscale('log', base=10) ax.xaxis.set_major_locator( ticker.LogLocator(base=10.0)) # Set x axis major tick for log10 ax.yaxis.set_major_locator( ticker.LogLocator(base=10.0)) # Set y axis major tick for log10 ax.xaxis.set_minor_formatter( ticker.NullFormatter()) # Set x axis minor tick unvisible # ax.xaxis.set_minor_formatter(ticker.ScalarFormatter()) # Set x axis minot tick as integ, Activate only for WS ax.yaxis.set_minor_formatter( ticker.NullFormatter()) # Set y axis minor tick unvisible ax.scatter(pmf_degree, pmf_prob, c='black', s=30, linewidths=0) # plot probability of degree distribution if R > 0: fit.power_law.plot_pdf(c='#766AFF', linestyle='dotted', linewidth=2, alpha=1) # plot power law fitting ax.tick_params(direction='in', which='major', axis='both', length=7, width=1, labelsize=20, pad=10) # Set major tick parameter ax.tick_params(direction='in', which='minor', axis='both', length=4, width=1, labelsize=20, pad=10) # Set minor tick parameter ax.set_xlabel('k', fontsize=25, labelpad=10) ax.set_ylabel('P(k)', fontsize=25, labelpad=10) ymin = min(pmf_prob) ymin_ = pow(10, round(np.log10(ymin))) - pow(10, round(np.log10(ymin) - 1)) ax.set_ylim(ymin_, ) log_fig_name = args.fig + '_Pk_plot.pdf' fig.savefig(log_fig_name, dpi=300, format='pdf', transparent=True) plt.clf() print(f'[SAVE] degree distribution figure (log-scale): {log_fig_name}') elapsed_time = time.time() - start_time print(f'[TIME]: {elapsed_time} sec') print(f'Completed!')