def graphical_abstract_figures(N=60, q=1, beta=0.1): """ Three dimensional process examples. """ a = 0 b = 1 m = [[a, b, b], [b, a, b], [b, b, a]] mu = (3. / 2) * 1. / N fitness_landscape = linear_fitness_landscape(m) incentive = fermi(fitness_landscape, beta=beta, q=q) edges = incentive_process.multivariate_transitions(N, incentive, num_types=3, mu=mu) d = stationary_distribution(edges, iterations=None) figure, tax = ternary.figure(scale=N) tax.heatmap(d, scale=N) tax.savefig(filename="ga_stationary.eps", dpi=600) d = expected_divergence(edges, q_d=0) figure, tax = ternary.figure(scale=N) tax.heatmap(d, scale=N) tax.savefig(filename="ga_d_0.eps", dpi=600) d = expected_divergence(edges, q_d=1) figure, tax = ternary.figure(scale=N) tax.heatmap(d, scale=N) tax.savefig(filename="ga_d_1.eps", dpi=600)
def bomze_figures(N=60, beta=1, process="incentive", directory=None): """ Makes plots of the stationary distribution and expected divergence for each of the plots in Bomze's classification. """ if not directory: directory = "bomze_paper_figures_%s" % process ensure_directory(directory) for i, m in enumerate(bomze_matrices()): mu = 3./2 * 1./N fitness_landscape = linear_fitness_landscape(m) incentive = fermi(fitness_landscape, beta=beta) edges = incentive_process.multivariate_transitions(N, incentive, num_types=3, mu=mu) d1 = stationary_distribution(edges) filename = os.path.join(directory, "%s_%s_stationary.eps" % (i, N)) figure, tax = ternary.figure(scale = N) tax.heatmap(d1) tax.savefig(filename=filename) pyplot.close(figure) for q_d in [0., 1.]: d2 = expected_divergence(edges, q_d=q_d) filename = os.path.join(directory, "%s_%s_%s.eps" % (i, N, q_d)) figure, tax = ternary.figure(scale = N) tax.heatmap(d2) tax.savefig(filename=filename) pyplot.close(figure)
def bomze_figures(N=60, beta=1, process="incentive", directory=None): """ Makes plots of the stationary distribution and expected divergence for each of the plots in Bomze's classification. """ if not directory: directory = "bomze_paper_figures_%s" % process ensure_directory(directory) for i, m in enumerate(bomze_matrices()): mu = 3. / 2 * 1. / N fitness_landscape = linear_fitness_landscape(m) incentive = fermi(fitness_landscape, beta=beta) edges = incentive_process.multivariate_transitions(N, incentive, num_types=3, mu=mu) d1 = stationary_distribution(edges) filename = os.path.join(directory, "%s_%s_stationary.eps" % (i, N)) figure, tax = ternary.figure(scale=N) tax.heatmap(d1) tax.savefig(filename=filename) pyplot.close(figure) for q_d in [0., 1.]: d2 = expected_divergence(edges, q_d=q_d) filename = os.path.join(directory, "%s_%s_%s.eps" % (i, N, q_d)) figure, tax = ternary.figure(scale=N) tax.heatmap(d2) tax.savefig(filename=filename) pyplot.close(figure)
def graphical_abstract_figures(N=60, q=1, beta=0.1): """ Three dimensional process examples. """ a = 0 b = 1 m = [[a, b, b], [b, a, b], [b, b, a]] mu = (3. / 2 ) * 1. / N fitness_landscape = linear_fitness_landscape(m) incentive = fermi(fitness_landscape, beta=beta, q=q) edges = incentive_process.multivariate_transitions(N, incentive, num_types=3, mu=mu) d = stationary_distribution(edges, iterations=None) figure, tax = ternary.figure(scale=N) tax.heatmap(d, scale=N) tax.savefig(filename="ga_stationary.eps", dpi=600) d = expected_divergence(edges, q_d=0) figure, tax = ternary.figure(scale=N) tax.heatmap(d, scale=N) tax.savefig(filename="ga_d_0.eps", dpi=600) d = expected_divergence(edges, q_d=1) figure, tax = ternary.figure(scale=N) tax.heatmap(d, scale=N) tax.savefig(filename="ga_d_1.eps", dpi=600)
def random_heatmap(scale=4): d = generate_random_heatmap_data(scale) figure, tax = ternary.figure(scale=scale, ax=ax) tax.heatmap(d, style="t") tax.boundary(color='black') tax.set_title("Heatmap Test: Triangular") ax = pyplot.subplot(gs[0, 1]) figure, tax = ternary.figure(scale=scale, ax=ax) tax.heatmap(d, style="d") tax.boundary(color='black') tax.set_title("Heatmap Test Dual") pyplot.show()
def random_heatmap(scale=4): d = generate_random_heatmap_data(scale) figure, tax = ternary.figure(scale=scale, ax=ax) tax.heatmap(d, style="t") tax.boundary(color='black') tax.set_title("Heatmap Test: Triangular") ax = pyplot.subplot(gs[0,1]) figure, tax = ternary.figure(scale=scale, ax=ax) tax.heatmap(d, style="d") tax.boundary(color='black') tax.set_title("Heatmap Test Dual") pyplot.show()
def plot_dictionary(s, ax=None): """ Plot two or three dimensional dictionary on a simplex partition, such as a stationary distribution. """ num_types = len(s.keys()[0]) N = sum(s.keys()[0]) if not ax: fig, ax = pyplot.subplots() if num_types == 2: domain = list(range(0, N+1)) values = [] for i in domain: state = (i, N-i) values.append(s[state]) if not ax: fig, ax = pyplot.subplots() pyplot.plot(domain, values) if num_types == 3: fig, tax = ternary.figure(scale=N, ax=ax) tax.heatmap(s, style='d')
def figure_factory(background=False): figure, tax = ternary.figure(scale=1.0) figure.set_size_inches(6, 6) if background: tax.set_title("", fontsize=20) tax.bottom_axis_label("Case", fontsize=14, offset=-0.05) tax.left_axis_label("Control", fontsize=14) tax.right_axis_label("Shared", fontsize=14) tax.ticks(axis='lbr', linewidth=1, multiple=0.1, tick_formats="%.1f") tax.gridlines(multiple=0.05, color="grey") else: tax.get_axes().axis('off') tax.clear_matplotlib_ticks() tax.line((0, 1, 0), (0.5, 0, 0.5), linewidth=.5, color='black', linestyle="-") figure.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) tax._redraw_labels() return figure, tax
def conc_err_plot(fname): """Plots the error in the CE data. This plots the error in the CE predictions within a ternary concentration diagram. Parameters ---------- fname : string containing the input file name. """ energies = _read_data(fname) enthalpy = _energy_to_enthalpy(energies) this_errors = _find_error(enthalpy) points = [] colors = [] for er in this_errors: concs = er[0] points.append((concs[0] * 100, concs[1] * 100, concs[2] * 100)) colors.append(er[1]) scale = 100 figure, tax = ternary.figure(scale=scale) tax.boundary(linewidth=1.0) tax.set_title("Errors in Convex Hull Predictions.", fontsize=20) tax.gridlines(multiple=10, color="blue") tax.scatter(points, vmax=max(colors), colormap=plt.cm.viridis, colorbar=True, c=colors, cmap=plt.cm.viridis) tax.show()
def plot_dictionary(s, ax=None): """ Plot two or three dimensional dictionary on a simplex partition, such as a stationary distribution. """ num_types = len(s.keys()[0]) N = sum(s.keys()[0]) if not ax: fig, ax = pyplot.subplots() if num_types == 2: domain = list(range(0, N + 1)) values = [] for i in domain: state = (i, N - i) values.append(s[state]) if not ax: fig, ax = pyplot.subplots() pyplot.plot(domain, values) if num_types == 3: fig, tax = ternary.figure(scale=N, ax=ax) tax.heatmap(s, style='d')
def plot_simplex(self, data, title, filename, tax=None, cb_kwargs={}): if tax is None: fig, tax = ternary.figure(scale=self.simplex_range) fig.set_size_inches(10, 8) else: fig = None tax.heatmap(data, style="triangular", **cb_kwargs) tax.boundary(linewidth=2.0) tax.set_title(title) tax.bottom_axis_label("Delay weight $\\alpha$", fontsize=12, offset=0.14) tax.right_axis_label("Throughput weight $\\beta$", fontsize=12, offset=0.14) tax.left_axis_label("Flow maximization $\\gamma$", fontsize=12, offset=0.14) tax.ticks(axis='lbr', linewidth=1, multiple=5) tax.clear_matplotlib_ticks() tax._redraw_labels() if fig is not None: if self.headless: fig.savefig( os.path.join(self.image_path, self.folder, filename)) plt.close(fig) else: return fig
def plot(self, filename, panel_list, ancestries_df): dataset_label, _ = self._unique_dataset_and_K_check(ancestries_df) dataset = Dataset(dataset_label) population_order = Dataset.used_populations() rows, cols = 1, len(panel_list) width, height = self.PLOT_SIZE fig = plt.figure(figsize=(cols * width, rows * height), dpi=30) fig.set_size_inches((cols*width), (rows*height)) ax_ids = (np.arange(rows * cols) + 1).tolist()[::-1] # One subplot per panel for panel in panel_list: df_lite = ancestries_df.xs(panel.label, level="panel") df_lite = df_lite.reset_index(drop=True).set_index("population") plot_title = "Dataset: {}\n{}".format(dataset.name, panel.name) ax = fig.add_subplot(rows, cols, ax_ids.pop()) fig, tax = ternary.figure(scale=1, ax=ax) df_lite = df_lite.loc[population_order] df_lite = df_lite[["EUR", "AFR", "AMR"]].dropna() df_grouped = df_lite.groupby(level="population", sort=False) for population, df_pop_group in df_grouped: tax.scatter( df_pop_group.values, label=population, s=45, alpha=0.75, color=population_colors(population), marker=population_markers(population) ) self._ternary_plot_aesthetics(tax, plot_title, df_lite) makedirs(self.PLOTS_DIR, exist_ok=True) plt.savefig(join(self.PLOTS_DIR, filename), bbox_inches="tight")
def four_dim_figures(N=30, beta=1., q=1.): """ Four dimensional example. Three dimensional slices are plotted for illustation. """ m = [[0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1], [0, 0, 0, 1]] num_types = len(m[0]) fitness_landscape = linear_fitness_landscape(m) mu = 4. / 3 * 1. / N incentive = fermi(fitness_landscape, beta=beta, q=q) edges = incentive_process.multivariate_transitions(N, incentive, num_types=num_types, mu=mu) d1 = expected_divergence(edges, q_d=0, boundary=True) d2 = stationary_distribution(edges) # We need to slice the 4dim dictionary into three-dim slices for plotting. for slice_index in range(4): for d in [d1, d2]: slice_dict = slice_dictionary(d, N, slice_index=3) figure, tax = ternary.figure(scale=N) tax.heatmap(slice_dict, style="d") pyplot.show()
def basic_example(): # Projection dynamic. initial_state = normalize(numpy.array([1, 1, 4])) m = rock_scissors_paper(a=1., b=-2.) fitness = linear_fitness(m) incentive = replicator_incentive_power(fitness, 0) mu = uniform_mutation_matrix(3, ep=0.2) t = compute_trajectory(initial_state, incentive, escort=power_escort(0), iterations=10000, verbose=True, mu=mu) figure, tax = ternary.figure() tax.plot(t, linewidth=2, color="black") tax.boundary() ## Lyapunov Quantities pyplot.figure() # Replicator Lyapunov e = normalize(numpy.array([1, 1, 1])) v = [kl_divergence(e, x) for x in t] pyplot.plot(range(len(t)), v, color='b') d = q_divergence(0) v = [d(e, x) for x in t] pyplot.plot(range(len(t)), v, color='r') pyplot.show()
def conc_err_plot(fname): """Plots the error in the CE data. This plots the error in the CE predictions within a ternary concentration diagram. Parameters ---------- fname : string containing the input file name. """ energies = _read_data(fname) enthalpy = _energy_to_enthalpy(energies) this_errors = _find_error(enthalpy) points = [] colors = [] for er in this_errors: concs = er[0] points.append((concs[0]*100,concs[1]*100,concs[2]*100)) colors.append(er[1]) scale = 100 figure, tax = ternary.figure(scale=scale) tax.boundary(linewidth = 1.0) tax.set_title("Errors in Convex Hull Predictions.",fontsize=20) tax.gridlines(multiple=10,color="blue") tax.scatter(points,vmax=max(colors),colormap=plt.cm.viridis,colorbar=True,c=colors,cmap=plt.cm.viridis) tax.show()
def plot_3way(scale, title, data, color, fname, vmax=100, vmin=-100): # afig, ax = plt.subplots(figsize=(8,6)) # figure, tax = ternary.figure(ax, scale=scale) figure, tax = ternary.figure(scale=scale) figure.set_dpi(300) tax.boundary(linewidth=2.0) tax.gridlines(color="black", multiple=5) # tax.gridlines(color="grey", multiple=1, linewidth=0.5) fontsize = 17 tax.set_title(title, fontsize=fontsize + 2, y=1.03) tax.clear_matplotlib_ticks() plt.axis('off') tax.left_axis_label("% Trans. Raising Input", fontsize=fontsize, offset=0.14) tax.right_axis_label("% Canon. Raising Input", fontsize=fontsize, offset=0.14) tax.bottom_axis_label("% Non-Productive Raising Input", fontsize=fontsize, offset=0.10) tax.ticks(axis='lbr', linewidth=1, multiple=10, offset=0.025, fontsize=14) hax = tax.heatmap(data, scale=scale, cmap=color, vmax=vmax, vmin=vmin) # hax.cbar.ax.tick_params(labelsize=20) tax._redraw_labels() ternary.plt.savefig(fname) ternary.plt.show()
def ternary_heatmapping( x_values: np.ndarray, y_values: np.ndarray, i_values: np.ndarray, number_of_bins: int, scale_divider: float = 1.0, ax: Optional[Axes] = None, ) -> Tuple[Figure, ternary.TernaryAxesSubplot]: """ Plot ternary heatmap. Modified from: https://github.com/marcharper/python-ternary/issues/81 """ scale = number_of_bins / scale_divider histogram, _ = np.histogramdd( (x_values, y_values, i_values), bins=(number_of_bins, number_of_bins, number_of_bins), range=((0, 1), (0, 1), (0, 1)), ) histogram_normed = histogram / np.sum(histogram) # 3D smoothing and interpolation kde = gaussian_filter(histogram_normed, sigma=2) interp_dict = dict() binx = np.linspace(0, 1, number_of_bins) for i in range(len(binx)): for j in range(len(binx)): for k in range(len(binx)): interp_dict[(i, j, k)] = kde[i, j, k] fig, tax = ternary.figure(ax=ax, scale=scale) tax.heatmap(interp_dict) return fig, tax
def buildPettijohnSST(): scale = 100 figure, tax = ternary.figure(scale=scale) figure.set_size_inches(10, 10) tax.set_title("Pettijohn", fontsize=20) tax.boundary(linewidth=2.0) tax.gridlines(multiple=5, color="black") tax.left_axis_label("Feldespar", fontsize=15) tax.right_axis_label("Quartz", fontsize=15) tax.bottom_axis_label("Lithics", fontsize=15) p1 = (5, 90, 5) p1_1 = (5, 95, 0) p1_2 = (0, 95, 5) p2 = (75, 0, 25) p3 = (50, 0, 50) p4 = (25, 0, 75) tax.line(p1_2, p1, linewidth=3., color='k', linestyle="-") tax.line(p1, p3, linewidth=3., color='k', linestyle="-") tax.line(p1_1, p1, linewidth=3., color='k', linestyle="-") tax.line((0, 75), (25, 50), linewidth=3., color='k', linestyle="-") tax.line((25, 50), (25, 75), linewidth=3., color='k', linestyle="-") figure.gca().text(24, 75, 'Subarkose', fontsize=15, rotation=0) figure.gca().text(61, 75, 'Sublitharenite', fontsize=15, rotation=0) figure.gca().text(55, 85, 'Quartzarenite', fontsize=15, rotation=0) figure.gca().text(25, 20, 'Arkosic\narenite', fontsize=15, rotation=0) figure.gca().text(65, 20, 'Lithic\narenite', fontsize=15, rotation=0) tax.ticks(axis='lbr', linewidth=1, multiple=5) tax.clear_matplotlib_ticks() figure.gca().axis('off') return figure, tax
def ternary_from_data(data, elems=["Left", "Center", "Right"], scale=32): _, ax = plt.subplots() # Make the plot fig, tax = ternary.figure(scale=scale, ax=ax) tax.gridlines(color="black", multiple=10) tax.boundary(linewidth=1) # Generate the heatmap sc = heatmap(data, scale, cmap=make_cmap(), ax=ax, vmin=0.5, vmax=1, colorbar=True) # Make it prettier plt.axis('off') ax.text(1.05 * scale, -0.05 * scale, elems[0], ha='right', fontsize=12) # 1st elem ax.text(.50 * scale, .90 * scale, elems[1], ha='center', fontsize=12) # 2nd elem ax.text(-.05 * scale, -.05 * scale, elems[2], ha='left', fontsize=12) # 3rd elem
def buildCong(): scale = 100 figure, tax = ternary.figure(scale=scale) figure.set_size_inches(10, 10) tax.set_title("Gravel and Conglomerates", fontsize=20) tax.boundary(linewidth=2.0) tax.gridlines(multiple=5, color="black") tax.left_axis_label("Mud", fontsize=15) tax.right_axis_label("Gravel", fontsize=15) tax.bottom_axis_label("Sand", fontsize=15) tax.horizontal_line(80, c='k', lw=3) tax.horizontal_line(30, c='k', lw=3) tax.horizontal_line(5, c='k', lw=3) tax.line((50, 0), (10, 80), linewidth=3., color='k', linestyle="-") tax.line((90, 0), (18, 80), linewidth=3., color='k', linestyle="-") tax.line((5, 5), (5, 0), linewidth=3., color='k', linestyle="-") figure.gca().text(-1, -5, 'Mud-', fontsize=15, rotation=0) figure.gca().text(20, 1, 'Sandy mud-', fontsize=15, rotation=0) figure.gca().text(60, 1, 'Muddy sand-', fontsize=15, rotation=0) figure.gca().text(91, -5, 'Sand-', fontsize=15, rotation=0) figure.gca().text(30, 10, 'Gravelly\nmud-', fontsize=15, rotation=0) figure.gca().text(60, 10, 'Gravelly\nmuddy sand-', fontsize=15, rotation=0) figure.gca().text(30, 42, 'Muddy\ngravel/cong', fontsize=15, rotation=0) figure.gca().text(51, 40, 'Muddy\nsandy\ngravel/cong.', fontsize=15, rotation=0) figure.gca().text(61, 75, 'Gravel/Cong', fontsize=15, rotation=0) figure.gca().text(73, 55, 'Sandy\ngravel/cong', fontsize=15, rotation=0) figure.gca().text(94, 15, 'Gravelly\nsand-', fontsize=15, rotation=0) tax.ticks(axis='lbr', linewidth=1, multiple=5) tax.clear_matplotlib_ticks() figure.gca().axis('off') return figure, tax
def _plotTernaryMixture_(self,cmap = 'viridis'): ''' When there are three parents, plot the value of the comparison function in a ternary plot ''' #Create a ternary figure figure, tax = ternary.figure(scale = 100.0) ## Boundary and Gridlines # Draw Boundary and Gridlines tax.boundary(linewidth=2.0) # Set Axis labels and Title tax.left_axis_label('% '+self.parentNames[2], fontsize=13) tax.right_axis_label('% '+self.parentNames[1], fontsize=13) tax.bottom_axis_label('% '+self.parentNames[0], fontsize=13) # Set ticks tax.ticks(axis='lbr', linewidth=1, multiple=10) # Remove default Matplotlib Axes tax.clear_matplotlib_ticks() d = dict() for i,mixCoeff in enumerate(self.mixingCoeffs): d[(round(mixCoeff[0],3)*100.0,round(mixCoeff[1],3)*100.0,round(mixCoeff[2],3)*100.0)] = self.mixtureFunctionValue[i] tax.heatmap(d, style='hexagonal',cmap = cmap) bestFit = self.mixingCoeffs[0] tax.scatter([(round(bestFit[0],3)*100.0,round(bestFit[1],3)*100.0,round(bestFit[2],3)*100.0)], marker='o', lw=3, color='black') # Save the current figure to a temporary PDF file tax.savefig(os.path.join(RESULT_FOLDER, 'temp.pdf')) tax.close() return tax
def ternary_plot(points, title): import ternary #tax is the axes object #For more information please vist https://github.com/marcharper/python-ternary figure, tax = ternary.figure(scale=100) # Remove default Matplotlib Axes tax.clear_matplotlib_ticks() #formatting the ternary diagram left_kwargs = {'color': 'blue'} right_kwargs = {'color': 'red'} tax.set_title(title, fontsize=20) tax.boundary(linewidth=2.0) tax.gridlines(color="black", multiple=5, left_kwargs=left_kwargs, right_kwargs=right_kwargs) #should be three stack of three different lines tax.scatter(points, linewidth=1) #axis settings fontsize = 10 tax.left_axis_label("%Clay", fontsize=fontsize) tax.right_axis_label("%Silt", fontsize=fontsize) tax.bottom_axis_label("%Sand", fontsize=fontsize) tax.ticks(axis='lbr', linewidth=1, multiple=10, clockwise=True) tax.get_axes().axis('off') #present ternary.plt.show()
def plot_ternary(av_df, labels_ordered): scale = 1 fig, ax = plt.subplots() figure, tax = ternary.figure(ax=ax, scale=scale) # figure.set_size_inches(10, 10) # Draw Boundary and Gridlines tax.boundary(linewidth=2.0) tax.gridlines(color="blue", multiple=0.1) # Set Axis labels and Title fontsize = 20 # tax.set_title("Various Lines", fontsize=20) tax.left_axis_label(labels_ordered[1], fontsize=fontsize) tax.right_axis_label(labels_ordered[2], fontsize=fontsize) tax.bottom_axis_label(labels_ordered[0], fontsize=fontsize) # Draw lines parallel to the axes # tax.horizontal_line(16) # tax.left_parallel_line(10, linewidth=2., color='red', linestyle="--") # tax.right_parallel_line(20, linewidth=3., color='blue') # Draw an arbitrary line, ternary will project the points for you p1 = (0.2, 0.35, 0.45) p2 = (0, 0, 1) tax.line(p1, p2, linewidth=3., marker='s', color='green', linestyle=":") ticks = list(np.arange(0, 1.1, 0.1)) tax.ticks(ticks=ticks, axis='brl', multiple=0.1, tick_formats="%0.1f") tax.clear_matplotlib_ticks() plt.tight_layout() plt.show()
def buildProvenancePlot(): #(Lithics, Qtz, Fs) scale = 100 figure, tax = ternary.figure(scale=scale) figure.set_size_inches(10, 10) tax.set_title("Tectonic Provenance", fontsize=20) tax.boundary(linewidth=2.0) tax.gridlines(multiple=5, color="black") tax.left_axis_label("Feldespar", fontsize=18) tax.right_axis_label("Quartz", fontsize=18) tax.bottom_axis_label("Lithics", fontsize=18) p1 = (75, 25, 0) p2 = (0, 100 - 45, 45) tax.line(p1, p2, linewidth=3., color='k', linestyle="-") q1 = (3, 97, 0) q2 = (15, 0, 100 - 15) tax.line(q1, q2, linewidth=3., color='k', linestyle="-") tax.line((0, 100 - 18), (5, 80), linewidth=3., color='k', linestyle="-") tax.line((75, 25, 0), (50, 0), linewidth=3., color='k', linestyle="-") tax.line((13, 18), (54, 33.5), linewidth=3., color='k', linestyle="-") tax.ticks(axis='lbr', linewidth=1, multiple=5) tax.clear_matplotlib_ticks() figure.gca().text(21, 80, 'Craton Interior', fontsize=15, color='k') figure.gca().text(15, 60, 'Transitional\nContinental', fontsize=15, color='k') figure.gca().text(-5, 20, 'Basement\nUplift', fontsize=15, color='k') figure.gca().text(50, 50, 'Recycled\nOrogenic', fontsize=15, color='k') figure.gca().text(35, 25, 'Dissected\nArc', fontsize=15, color='k') figure.gca().text(40, 10, 'Transitional\nArc', fontsize=15, color='k') figure.gca().text(70, 2, 'Undissected\nArc', fontsize=15, color='k') figure.gca().axis('off') return figure, tax
def plot(data, figure=None, **kwargs): if figure is None: fig, tax = ternary.figure() else: fig, tax = figure gammaData = np.ones(len(data[:, 0])) - data[:, 0] - data[:, 1] # Plot curve tax.plot(np.stack((data[:, 0], gammaData, data[:, 1]), axis=1), **kwargs)
def streck76_ol_2px(*puntos): fig, tax = tr.figure(scale=100) fig.set_size_inches(12, 12) tax.set_title( "Diagrama de clasificación de rocas plutónicas (Streckeisen 1976)", pad=50, Fontsize=20) tax.gridlines(multiple=10, color="k") tax.gridlines(5) tax.get_axes().axis('off') tax.horizontal_line(40) tax.left_parallel_line(90) tax.horizontal_line(90) tax.right_parallel_line(90) tax.ticks(multiple=10) tax.line([5, 90], [90, 5]) tax.line([5, 5], [5, 90]) tax.line([90, 5], [5, 5, 90]) tax.line([65, 40], [160, 40], ls='dashed', color='k') tax.left_corner_label("Opx", Fontsize=18, position=(-0.02, 0.05, 0)) tax.right_corner_label("Cpx", Fontsize=18, position=(0.97, 0.05, 0)) tax.top_corner_label("Ol", Fontsize=18, offset=0.18) coordenadas = [[2, 95], [2.5, 60], [20, 60], [37, 60], [2.5, 20], [40, 20], [77, 20], [3, 2.5], [47, 2.5], [93, 2.5]] for indice, coordenada in enumerate(coordenadas): tax.annotate(str(indice + 1), (coordenada[0], coordenada[1]), fontsize=9) indices = '''1- Dunita 2- Hazburguita 3- Lherzolita 4- Wehrlita 5- Ortopiroxenita olivínica 6- Websterita olivínica 7- Clinoperoxenita olivínica 8- Ortopiroxenita 9- Websterita 10- Clinopiroxenita''' tax.annotate(indices, position=(40, 100, 0), size=10, ha='left', va='top', bbox=dict(boxstyle='round', fc='w')) for punto in puntos: tax.scatter([[float(punto[0]), float(punto[1]), float(punto[2])]], label=punto[3]) fig.legend(fontsize=10, bbox_to_anchor=(0.18, 0.8), bbox_transform=fig.transFigure).get_frame().set_edgecolor('k') tax.show()
def streck76_plut_maf_hbl(*puntos): fig, tax = tr.figure(scale=100) fig.set_size_inches(12, 12) tax.set_title( "Diagrama de clasificación de rocas gabróideas con hornblenda (Streckeisen 1976)", pad=50, Fontsize=20) tax.gridlines(multiple=10, color="k") tax.gridlines(5) tax.get_axes().axis('off') tax.horizontal_line(10) tax.horizontal_line(90) tax.line([5, 65], [70, 65], color='r') tax.line([5, 35], [100, 35], color='r') tax.ticks(multiple=10) tax.line([5, 10], [5, 90]) tax.line([50, 0], [45, 10]) tax.line([85, 10], [5, 90]) tax.left_parallel_line(90) tax.right_parallel_line(90) tax.left_corner_label("Px", Fontsize=18, position=(-0.02, 0.05, 0)) tax.right_corner_label("Hbl", Fontsize=18, position=(0.97, 0.05, 0)) tax.top_corner_label("Pl", Fontsize=18, offset=0.18) coordenadas = [[3, 93], [2, 50], [25, 50], [46.5, 50], [3, 4], [25, 4], [70, 4], [93, 4]] for indice, coordenada in enumerate(coordenadas): tax.annotate(str(indice + 1), (coordenada[0], coordenada[1]), fontsize=9) indices = '''1- Anortosita 2- Gabro, Gabronorita, norita 3- Gabro/Gabronorita/norita de hornblenda y piroxeno 4- Gabro hornblendico 5- Piroxenita rica en plagioclasa 6- Piroxenita de hornblenda rica en plagioclasa 7- Hornblendita de piroxeno rica en plagioclasa 8- Hornblendita rica en plagioclasa ''' tax.annotate(indices, position=(40, 100, 0), size=10, ha='left', va='top', bbox=dict(boxstyle='round', fc='w')) for punto in puntos: tax.scatter([[float(punto[0]), float(punto[1]), float(punto[2])]], label=punto[3]) fig.legend(fontsize=10, bbox_to_anchor=(0.18, 0.8), bbox_transform=fig.transFigure).get_frame().set_edgecolor('k') tax.show()
def plot_tern(data_point): # Scatter Plot scale = 100 figure, tax = ternary.figure(scale=scale) figure.set_size_inches(10, 10) tax.set_title("Neon Isotopes", fontsize=20) tax.boundary(linewidth=2.0) tax.gridlines(multiple=10, color="black") tax.left_axis_label("Neon-22", offset=0.1) tax.right_axis_label("Neon-21", offset=0.1) tax.bottom_axis_label("Neon-20", offset=-0.05) # Air points = [] points.append([90.48, 00.27, 09.25]) tax.scatter(points, marker='s', color='red', label="Air") # Cosmogenic (Quartz; Schaefer et al. 1999) points = [] points.append([35.59, 28.47, 35.94]) tax.scatter(points, marker='s', color='green', label="Cosmogenic (Quartz)") # Cosmogenic (Pyroxene; Schaefer et al. 1999) points = [] points.append([29.67, 32.64, 37.69]) tax.scatter(points, marker='s', color='blue', label="Cosmogenic (Pyroxene)") # Mantle points = [] points.append([92.80, 00.47, 06.73]) tax.scatter(points, marker='s', color='purple', label="Mantle") # Nucleogenic (Bulk Crustal) points = [] points.append([08.39, 89.73, 01.88]) tax.scatter(points, marker='s', color='grey', label="Nucleogenic (Bulk Crust)") points = [] points.append(data_point) tax.scatter(points, marker='s', color='black', label="Data") tax.legend() tax.ticks(axis='lbr', multiple=10, linewidth=1, offset=0.012) tax.clear_matplotlib_ticks() tax.show()
def QFOth_ternary_plot(self, selected_phi_classes=None, save_filename=None): """Ternary diagram plot of pcg's modal mineralogy with trajectory along the model's steps. A=pcg_Q, B=pcg_PK, C=pcg_BOA. Data has been grouped by whole phi grain size classes. Parameters: ----------- selected_phi_classes : None or list (optional) List of phi classes to plot; defaults to None so that all phi classes are plotted. save_filename : str (optional) Name to use for saving figure; defaults to None so that no figure is saved. """ # Calculate data T_norm = self.calculate_QFOth_data() # Filter data if selected_phi_classes is None: selected_phi_classes = self.unit_phi_classes # Plot data fig, ax = plt.subplots(figsize=(12, 10.8)) figure, tax = ternary.figure(ax=ax, scale=1.0) tax.boundary() tax.gridlines(multiple=0.2, color="black") # tax.set_title("QFR plot", fontsize=20) fontsize = 12 tax.right_corner_label("Others", fontsize=fontsize) tax.top_corner_label("Quartz", fontsize=fontsize) tax.left_corner_label("Feldspar", fontsize=fontsize) points = [] # Get data for p, phi in enumerate(T_norm): if self.unit_phi_classes[p] in selected_phi_classes: points = phi # Plot the data tax.plot(points, linewidth=2.0, label=f"{self.unit_phi_classes[p]}_phi", marker='o', color=plt.cm.tab20(p)) tax.ticks(axis='lbr', multiple=0.2, linewidth=1, tick_formats="%.1f") tax.legend(loc=1) plt.axis('off') # plt.tight_layout() if save_filename: tax.savefig( f"_FIGURES/ternary_diagrams/QFO_ternary_plot_{save_filename}.pdf" ) tax.show()
def folk_arena_arcilla(*puntos): fig, tax = tr.figure(scale=100) fig.set_size_inches(12, 12) tax.set_title( "Diagrama de clasificación textural de rocas siliciclásticas (Folk 1954)", pad=50, Fontsize=20) tax.gridlines(multiple=10, color="k") tax.gridlines(5) tax.get_axes().axis('off') tax.horizontal_line(10) tax.horizontal_line(50) tax.horizontal_line(90) tax.ticks(multiple=10) tax.line([(100 / 3), 0], intersec([(100 / 3), 0], [0, 100], 90)) tax.line([(100 / 3 * 2), 0], intersec([(100 / 3 * 2), 0], [0, 100], 90)) tax.left_corner_label("Arcilla", Fontsize=18, position=(-0.02, 0.05, 0)) tax.right_corner_label("Limo", Fontsize=18, position=(0.97, 0.05, 0)) tax.top_corner_label("Arena", Fontsize=18, offset=0.18) coordenadas = [[2, 95], [5, 70], [15, 70], [25, 70], [12, 30], [35, 30], [60, 30], [17, 5], [47, 5], [80, 5]] for indice, coordenada in enumerate(coordenadas): tax.annotate(str(indice + 1), (coordenada[0], coordenada[1]), fontsize=9) indices = '''1- Arenisca 2- Arenisca arcillosa 3- Arenisca lodosa 4- Arenisca limosa 5- Arcillolita arenosa 6- Lodolita arenosa 7- Limolita arenosa 8- Arcillolita 9- Lodolita 10- Limolita''' tax.annotate(indices, position=(40, 100, 0), size=10, ha='left', va='top', bbox=dict(boxstyle='round', fc='w')) for punto in puntos: tax.scatter([[float(punto[0]), float(punto[1]), float(punto[2])]], label=punto[3]) fig.legend(fontsize=10, bbox_to_anchor=(0.18, 0.8), bbox_transform=fig.transFigure).get_frame().set_edgecolor('k') tax.show()
def create_graphs(Ncomps, dpi): scale = 100 figure, tax = ternary.figure(scale=scale) figure, pax = ternary.figure(scale=scale) # Draw Boundary and Gridlines tax.boundary(linewidth=0.25) tax.gridlines(color="blue", multiple=10) pax.boundary(linewidth=0.55) pax.gridlines(color="blue", multiple=10) # Set Axis labels and Title fontsize = 10 tax.set_title("BaxCuyArz Composition diagram", fontsize=20) tax.left_axis_label("Ba", fontsize=fontsize) tax.right_axis_label("Cu", fontsize=fontsize) tax.bottom_axis_label("Ar", fontsize=fontsize) fontsize = 10 pax.set_title("BaxCuyArz Composition diagram", fontsize=20) pax.left_axis_label("Ba", fontsize=fontsize) pax.right_axis_label("Cu", fontsize=fontsize) pax.bottom_axis_label("Ar", fontsize=fontsize) p1 = [] with open("composition.dat") as handle: for line in handle: p1.append(list(map(float, line.split(' ')))) tax.scatter(p1) pax.scatter(p1) tax.legend() pax.ticks(axis='lbr', multiple=10, linewidth=1) for i in range(Ncomps): tax.annotate(str(p1[i]), (p1[i]), fontsize=7, rotation=10) tax.savefig('Ternary_with_labels.png', dpi) pax.savefig('Ternary_no_labels.png', dpi)
def plot_prediction_ternary(result, scale=100, multiple=20, plot_name=None): correct = result['correct'] wrong = result['wrong'] unknown = result['unknown'] fontsize = 12 axis_fontsize = 8 figure, tax = ternary.figure(scale=scale) #tax.set_title("Training Data", fontsize=20) tax.boundary(linewidth=1.0) tax.gridlines(multiple=multiple, color="blue") tax.left_axis_label("$C_{10}$", fontsize=fontsize) tax.right_axis_label("$C_{6}$", fontsize=fontsize) tax.bottom_axis_label("$C_{1}$", fontsize=fontsize) correct_points = correct[0] * scale wrong_points = wrong[0] * scale unknown_points = unknown[0] * scale correct_points = np.rint(correct_points) correct_points = correct_points.astype(int) wrong_points = np.rint(wrong_points) wrong_points = wrong_points.astype(int) unknown_points = np.rint(unknown_points) unknown_points = unknown_points.astype(int) if (correct_points.shape[0] > 0): tax.scatter(correct_points, s=1, color='red', label="Correct") if (wrong_points.shape[0] > 0): tax.scatter(wrong_points, s=3, color='blue', label="Wrong") if (unknown_points.shape[0] > 0): tax.scatter(unknown_points, s=2, color='green', label="Uncertain") tax.legend() tax.clear_matplotlib_ticks() tax.ticks(axis='lbr', linewidth=1, multiple=multiple, fontsize=8) tax._redraw_labels() for spine in plt.gca().spines.values(): spine.set_visible(False) if plot_name is None: plot_name = 'stab-prediction-result' file_name = plot_name + '.eps' tax.savefig(file_name) file_name = plot_name + '.pdf' tax.savefig(file_name)
def render_stationary(s): """ Renders a stationary distribution. """ # Put the stationary distribution into a dictionary d = dict() for state, value in s: d[state] = value N = sum(state) # Plot it figure, tax = ternary.figure(scale=N) tax.heatmap(d, scientific=True, style='d')
def draw_triangle_ax(self, ax): ancestries = self.admixture.result[3] fig, tax = ternary.figure(scale=1, ax=ax) ancestries = ancestries[["EUR", "AFR", "AMR"]].dropna() by_population = ancestries.groupby(level="population", sort=False) for population, df in by_population: tax.scatter(df.values, label=population, s=45, marker='o', color=self.colors[population]) plot_title = self._make_title(3).replace(' - ', '\n') self._ternary_plot_aesthetics(tax, plot_title, ancestries) return tax
def simplexPath(episodes, title=""): # Sample trajectory plot figure, tax = ternary.figure(scale=1.0) figure.set_size_inches(15, 15, forward=True) tax.boundary() tax.gridlines(multiple=0.2, color="black") tax.set_title(title, fontsize=20) points = [] # Plot the data tax.plot(episodes, linewidth=2.0, label="Curve") tax.ticks(axis='lbr', multiple=0.2, linewidth=1, tick_formats="%.1f") tax.legend() tax.show()
def plot_ternary_scatter(data_matrix): ### Scatter Plot scale = 1 figure, tax = ternary.figure(scale=scale) tax.set_title("Scatter Plot", fontsize=20) tax.boundary(linewidth=2.0) tax.gridlines(multiple=0.1, color="blue") # Plot a few different styles with a legend # points = [data_matrix] # tax.heatmap() tax.scatter(data_matrix, marker='s', color='red', label="Red Squares") tax.legend() tax.ticks(axis='lbr', linewidth=1, multiple=0.1)
def folk_comp(*puntos): fig, tax = tr.figure(scale=100) fig.set_size_inches(12, 12) tax.set_title( "Diagrama de clasificación composicional de rocas siliciclásticas (Folk 1974)", pad=50, Fontsize=20) tax.gridlines(multiple=10, color="k") tax.gridlines(5) tax.get_axes().axis('off') tax.horizontal_line(95) tax.horizontal_line(75) tax.ticks(multiple=10) tax.line([(100 / 4), 0], intersec([(100 / 4), 0], [0, 100], 75)) tax.line([(100 / 4 * 3), 0], intersec([(100 / 4 * 3), 0], [0, 100], 75)) tax.line([50, 0], intersec([50, 0], [0, 100], 95)) tax.left_corner_label("F", Fontsize=18, position=(-0.02, 0.05, 0)) tax.right_corner_label("L", Fontsize=18, position=(0.97, 0.05, 0)) tax.top_corner_label("Q", Fontsize=18, offset=0.18) coordenadas = [[1.1, 97], [3, 85], [11, 85], [7, 30], [25, 30], [45, 30], [60, 30]] for indice, coordenada in enumerate(coordenadas): tax.annotate(str(indice + 1), (coordenada[0], coordenada[1]), fontsize=9) indices = '''1- Cuarzoarenita 2- Sublitoarenita 3- Subarcosa 4- Litoarenita 5- Litoarenita Feldespática 6- Arcosa Lítica 7- Arcosa''' tax.annotate(indices, position=(40, 100, 0), size=10, ha='left', va='top', bbox=dict(boxstyle='round', fc='w')) for punto in puntos: tax.scatter([[float(punto[0]), float(punto[1]), float(punto[2])]], label=punto[3]) fig.legend(fontsize=10, bbox_to_anchor=(0.18, 0.8), bbox_transform=fig.transFigure).get_frame().set_edgecolor('k') tax.show()
def make_ternary_legend(elements): """Makes the legend for concentraition plots.""" scale = 100 data = _generate_heatmap_data(scale) figure, tax = ternary.figure(scale=100, permutation="210") tax.heatmap(data, colormap=False) tax.boundary(linewidth = 0.0) tax.right_corner_label(elements[0], position=(0.95,0.1), fontsize=16) tax.top_corner_label(elements[1], position=(-0.075,1.15), fontsize=16) tax.left_corner_label(elements[2], position=(-0.05,0.1), fontsize=16) plt.axis("off") plt.show()
def render_stationary(s): """ Renders a stationary distribution. """ # Put the stationary distribution into a dictionary d = dict() for state, value in s: d[state] = value N = sum(list(d.keys())[0]) # Plot it figure, tax = ternary.figure(scale=N) tax.heatmap(remove_boundary(d), scientific=True, style='triangular', cmap="jet") return tax
def plot_graph(points): ### Scatter Plot scale = 1 figure, tax = ternary.figure(scale=scale) tax.set_title("Scatter Plot", fontsize=20) tax.boundary(color="black", linewidth=0.5) #tax.gridlines(multiple=5, color="blue") # Plot a few different styles with a legend tax.scatter(points, marker='s', color='red', label="Red Squares") #points = random_points(30, scale=scale) #tax.scatter(points, marker='D', color='green', label="Green Diamonds") tax.legend() tax.ticks(axis='lbr', color="black", linewidth=1, multiple=0.1) tax.show()
def rps_figures(N=60, q=1, beta=1.): """ Three rock-paper-scissors examples. """ m = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]] num_types = len(m[0]) fitness_landscape = linear_fitness_landscape(m) for i, mu in enumerate([1./math.sqrt(N), 1./N, 1./N**(3./2)]): # Approximate calculation mu = 3/2. * mu incentive = fermi(fitness_landscape, beta=beta, q=q) edges = incentive_process.multivariate_transitions(N, incentive, num_types=num_types, mu=mu) d = stationary_distribution(edges, lim=1e-10) figure, tax = ternary.figure() tax.heatmap(d, scale=N) tax.savefig(filename="rsp_mu_" + str(i) + ".eps", dpi=600)
def draw(self, ax=None, setup=True, marker='o', color='k'): # pragma: no cover """ Plot the entropy triangle. Parameters ---------- ax : Axis or None The matplotlib axis to plot on. If none is provided, one will be constructed. setup : bool If true, labels, tick marks, gridlines, and a boundary will be added to the plot. Defaults to True. marker : str The matplotlib marker shape to use. color : str The color of marker to use. """ import ternary if ax is None: fig, ax = ternary.figure() fig.set_size_inches(10, 8) else: ax = ternary.TernaryAxesSubplot(ax=ax) if setup: ax.boundary() ax.gridlines(multiple=0.1) fontsize = 20 ax.set_title("Entropy Triangle", fontsize=fontsize) ax.left_axis_label(self.left_label, fontsize=fontsize) ax.right_axis_label(self.right_label, fontsize=fontsize) ax.bottom_axis_label(self.bottom_label, fontsize=fontsize) ax.ticks(axis='lbr', multiple=0.1, linewidth=1) ax.clear_matplotlib_ticks() ax.scatter(self.points, marker=marker, color=color) ax._redraw_labels() return ax
def basic_example(): # Projection dynamic. initial_state = normalize(numpy.array([1,1,4])) m = rock_scissors_paper(a=1., b=-2.) fitness = linear_fitness(m) incentive = replicator_incentive_power(fitness, 0) mu = uniform_mutation_matrix(3, ep=0.2) t = compute_trajectory(initial_state, incentive, escort=power_escort(0), iterations=10000, verbose=True, mu=mu) figure, tax = ternary.figure() tax.plot(t, linewidth=2, color="black") tax.boundary() ## Lyapunov Quantities pyplot.figure() # Replicator Lyapunov e = normalize(numpy.array([1,1,1])) v = [kl_divergence(e, x) for x in t] pyplot.plot(range(len(t)), v, color='b') d = q_divergence(0) v = [d(e, x) for x in t] pyplot.plot(range(len(t)), v, color='r') pyplot.show()
def ER_figure_beta3(N, m, mu, betas, iss_states, labels, stationary_beta=0.35, pickle_filename="figure_beta3.pickle"): """Varying Beta, three dimensional example""" ss = [] plot_data = [[] for _ in range(len(iss_states))] if os.path.exists(pickle_filename): with open(pickle_filename, 'rb') as f: plot_data = pickle.load(f) else: for beta in betas: print(beta) e, s = compute_entropy_rate( N=N, m=m, n=3, beta=beta, exact=False, mu=mu, lim=1e-10) ss.append(s) for i, iss_state in enumerate(iss_states): s_max = s[iss_state] plot_data[i].append((e, s_max, e / s_max)) with open(pickle_filename, 'wb') as f: pickle.dump(plot_data, f) gs = gridspec.GridSpec(3, 2) ax1, ax2, ax3 = plot_data_sub(betas, plot_data, gs, labels=labels, use_log=True, sci=False) ax3.set_xlabel("Strength of selection $\\beta$") ax2.legend(loc="upper right") # Plot example stationary ax4 = plt.subplot(gs[:, 1]) _, s = compute_entropy_rate( N=N, m=m, n=3, beta=stationary_beta, exact=False, mu=mu, lim=1e-15) _, tax = ternary.figure(ax=ax4, scale=N,) tax.heatmap(s, cmap="jet", style="triangular") tax.ticks(axis='lbr', linewidth=1, multiple=10, offset=0.015) tax.clear_matplotlib_ticks() ax4.set_xlabel("Population States $a_1 + a_2 + a_3 = N$")
def PrintTernary(AtPct, IshiiAtPct, IshiiAtPctSD): if ternary == None: print "For ternary plot please pip install python-ternary" return ### Now print a ternary plot if plt.fignum_exists(2): plt.figure(2) plt.close() fig, tax = ternary.figure(scale=100) tax.boundary(linewidth=4) tax.gridlines(color='black', multiple=10) tax.left_axis_label("Fe-S", fontsize=FontSizeBasis) tax.bottom_axis_label("Si", fontsize=FontSizeBasis) tax.right_axis_label("Mg", fontsize=FontSizeBasis) # Remove default matplotlib ticks. tax.ticks(axis='lbr', linewidth=1, multiple=10) tax.clear_matplotlib_ticks() # Compute and plot this point on the ternary for this composition FeminusS = AtPct[pb.Fe - 1] - AtPct[pb.S - 1] ThisPoint = array([FeminusS, AtPct[pb.Si - 1], AtPct[pb.Mg - 1]]).astype('float') ThisPoint = ThisPoint / sum(ThisPoint) * 100 ThisPoint = vstack((ThisPoint, ThisPoint)) # Seems to be a bug -- you need a minimum of two points... tax.scatter(ThisPoint, marker='.', s=300, alpha=0.5, color='blue', label="This Spectrum") # Compute and plot the point for the average of GEMS. FeminusS = IshiiAtPct[pb.Fe - 1] - IshiiAtPct[pb.S - 1] IshiiPoint = array([FeminusS, IshiiAtPct[pb.Si - 1], IshiiAtPct[pb.Mg - 1]]).astype('float') IshiiPoint = IshiiPoint / sum(IshiiPoint) * 100 IshiiPoint = vstack((IshiiPoint, IshiiPoint)) # Seems to be a bug -- you need a minimum of two points... tax.scatter(IshiiPoint, marker='.', s=300, alpha=0.5, color='red', label="Ishii et al., 2008") tax.legend() plt.title('At %')
def ternary_plot(points,title): import ternary #tax is the axes object #For more information please vist https://github.com/marcharper/python-ternary figure, tax = ternary.figure(scale =100) # Remove default Matplotlib Axes tax.clear_matplotlib_ticks() #formatting the ternary diagram left_kwargs = {'color': 'blue'} right_kwargs = {'color': 'red'} tax.set_title(title, fontsize=20) tax.boundary(linewidth=2.0) tax.gridlines(color="black", multiple=5, left_kwargs=left_kwargs,right_kwargs=right_kwargs) #should be three stack of three different lines tax.scatter(points,linewidth=1) #axis settings fontsize = 10 tax.left_axis_label("%Clay", fontsize=fontsize) tax.right_axis_label("%Silt", fontsize=fontsize) tax.bottom_axis_label("%Sand", fontsize=fontsize) tax.ticks(axis='lbr', linewidth=1, multiple= 10,clockwise= True) tax.get_axes().axis('off') #present ternary.plt.show()
def draw_ternary_plot(controls, rcontrols, filename): m = np.shape(controls)[0] n = 20 ten_per = int(floor(m/5.0)) swap_cols(controls, 2, 0) swap_cols(rcontrols, 2, 0) swap_cols(controls, 0, 1) swap_cols(rcontrols, 0, 1) first_ten_per = controls[range(0, ten_per),:] rfirst_ten_per = rcontrols[range(0, ten_per),:] rest = controls[range(ten_per, m),:] rrest = rcontrols[range(ten_per, m),:] figure, tax = ternary.figure(scale=1.0) tax.boundary(color='black') tax.plot(first_ten_per, linewidth=3, label="Weight cuts", color="#00d3e4") tax.plot(rfirst_ten_per, linewidth=3, label="Random cuts", color="#75b765") tax.plot(rest, linewidth=1, label="Weight cuts", color="#007e88") tax.plot(rrest, linewidth=1, label="Random cuts", color="#466d3c") tax.left_axis_label("No external dilation control") tax.right_axis_label("No source control") tax.bottom_axis_label("No internal dilation control") tax.legend() #tax.show() figure.savefig('graphs/ternary/'+filename+'-ternary.png')
# E210.append(float("%.3f" % float(row['x']))) # M210.append(float("%.3f" % float(row['y']))) # T210.append(float("%.3f" % float(row['z']))) # w210.append(float("%.3f" % float(row['w']))) point1=[(scale*0.3980599331366308,scale*0.3112164005027349,scale*0.2907236663606344)] point2=[(scale*0.34669820676138435,scale*0.3336302826666826,scale*0.31967151057193305)] point3=[(scale*0.55214511226237,scale*0.24397475401089158,scale*0.20388013372673847)] point4=[(scale*0.24397475401089158,scale*0.3784580469945782,scale*0.3775671989945304)] democratic=[(scale*1/3,scale*1/3,scale*1/3)] point5=[(scale*0.4494216595118771,scale*0.2888025183387871,scale*0.26177582214933576)] ice1=[(scale*0,scale*0.2,scale*0.8)] ice2=[(scale*0.18,scale*0.41,scale*0.41)] """ternary settings""" figure, d=t.figure(scale=scale) d.boundary(linewidth=2) d.gridlines(multiple=scale/10,color="blue",linewidth=0.2) d.set_title(r"source flavour composition ",fontsize=20) d.left_axis_label(r"$\nu_\tau$",offset=0.12,fontsize=20) d.right_axis_label(r"$\nu_\mu$",offset=0.12,fontsize=20) d.bottom_axis_label(r"$\nu_e$",offset=0,fontsize=20) d._redraw_labels() ticks = [round(i / float(10), 1) for i in range(10+1)] d.ticks(ticks=ticks) p.axis('off') """scatter version""" #max110=max(w110) #max100=max(w100) #max120=max(w120)
import ternary import matplotlib.pyplot as plt # Function to visualize for heat map def f(x): return 1.0 * x[0] / (1.0 * x[0] + 0.2 * x[1] + 0.05 * x[2]) # dictionary of axes colors for bottom (b), left (l), right (r) axes_colors = {'b': 'g', 'l': 'r', 'r':'b'} scale = 10 fig, ax = plt.subplots() ax.axis("off") figure, tax = ternary.figure(ax=ax, scale=scale) tax.heatmapf(f, boundary=False, style="hexagonal", cmap=plt.cm.get_cmap('Blues'), cbarlabel='Component 0 uptake', vmax=1.0, vmin=0.0) tax.boundary(linewidth=2.0, axes_colors=axes_colors) tax.left_axis_label("$x_1$", offset=0.16, color=axes_colors['l']) tax.right_axis_label("$x_0$", offset=0.16, color=axes_colors['r']) tax.bottom_axis_label("$x_2$", offset=-0.06, color=axes_colors['b']) tax.gridlines(multiple=1, linewidth=2, horizontal_kwargs={'color':axes_colors['b']}, left_kwargs={'color':axes_colors['l']}, right_kwargs={'color':axes_colors['r']},
return points def random_points(num_points=25, scale=40): points = [] for i in range(num_points): x = random.randint(1, scale) y = random.randint(0, scale - x) z = scale - x - y points.append((x, y, z)) return points if __name__ == '__main__': # Show Coordinates scale = 3 fig, tax = ternary.figure(scale=scale, permutation="120") points_lists = [[(0, 0, 3), (1, 0, 2), (2, 0, 1)], [(3, 0, 0), (2, 1, 0), (1, 2, 0)], [(0, 3, 0), (0, 2, 1), (0, 1, 2)], [(1, 1, 1)]] colors = ['b', 'r', 'g', 'black'] markers = ['o', 'v', '*', 'd'] for i, points in enumerate(points_lists): for point in points: tax.scatter([tuple(point)], color=colors[i], marker=markers[i]) tax.annotate("".join(map(str, point)), tuple(point), color=colors[i]) tax.gridlines(multiple=1.) ## Boundary and Gridlines scale = 40 fig, tax = ternary.figure(scale=scale)
def plot_ternary(self, T, scale=10): # pragma: no cover if not has_matplotlib: raise Exception('Optional dependency matplotlib is required for plotting') try: import ternary except: raise Exception('Optional dependency ternary is required for ternary plotting') if self.N != 3: raise Exception('Ternary plotting requires a mixture of exactly three components') P_values = [] def P_dew_at_T_zs(zs): zs = self.un_zero_zs(zs) self.flash(T=T, zs=zs, VF=0) P_values.append(self.P) return self.P def P_bubble_at_T_zs(zs): zs = self.un_zero_zs(zs) self.flash(T=T, zs=zs, VF=1) return self.P axes_colors = {'b': 'g', 'l': 'r', 'r':'b'} ticks = [round(i / float(10), 1) for i in range(10+1)] fig, ax = plt.subplots(1, 3, gridspec_kw = {'width_ratios':[4, 4, 1]}) ax[0].axis("off") ; ax[1].axis("off") ; ax[2].axis("off") for axis, f, i in zip(ax[0:2], [P_dew_at_T_zs, P_bubble_at_T_zs], [0, 1]): figure, tax = ternary.figure(ax=axis, scale=scale) figure.set_size_inches(12, 4) if not i: tax.heatmapf(f, boundary=True, colorbar=False, vmin=0) else: tax.heatmapf(f, boundary=True, colorbar=False, vmin=0, vmax=max(P_values)) tax.boundary(linewidth=2.0) tax.left_axis_label("mole fraction $x_2$", offset=0.16, color=axes_colors['l']) tax.right_axis_label("mole fraction $x_1$", offset=0.16, color=axes_colors['r']) tax.bottom_axis_label("mole fraction $x_3$", offset=-0.06, color=axes_colors['b']) tax.ticks(ticks=ticks, axis='rlb', linewidth=1, clockwise=True, axes_colors=axes_colors, offset=0.03) tax.gridlines(multiple=scale/10., linewidth=2, horizontal_kwargs={'color':axes_colors['b']}, left_kwargs={'color':axes_colors['l']}, right_kwargs={'color':axes_colors['r']}, alpha=0.5) norm = plt.Normalize(vmin=0, vmax=max(P_values)) sm = plt.cm.ScalarMappable(cmap=plt.get_cmap('viridis'), norm=norm) sm._A = [] cb = plt.colorbar(sm, ax=ax[2]) cb.locator = matplotlib.ticker.LinearLocator(numticks=7) cb.formatter = matplotlib.ticker.ScalarFormatter() cb.formatter.set_powerlimits((0, 0)) cb.update_ticks() plt.tight_layout() fig.suptitle("Bubble pressure vs composition (left) and dew pressure vs composition (right) at %s K, in Pa" %T, fontsize=14); fig.subplots_adjust(top=0.85) plt.show()
figure, tax = ternary.figure(scale=scale, ax=ax) tax.heatmap(d, style="t") tax.boundary(color='black') tax.set_title("Heatmap Test: Triangular") ax = pyplot.subplot(gs[0,1]) figure, tax = ternary.figure(scale=scale, ax=ax) tax.heatmap(d, style="d") tax.boundary(color='black') tax.set_title("Heatmap Test Dual") pyplot.show() if __name__ == '__main__': # Show Coordinates scale = 3 figure, tax = ternary.figure(scale=scale, permutation="120") points_lists = [[(0,0,3), (1,0,2), (2,0,1)], [(3,0,0), (2,1,0), (1,2,0)], [(0,3,0), (0,2,1), (0,1,2)], [(1,1,1)]] colors = ['b', 'r', 'g', 'black'] markers = ['o', 'v', '*', 'd'] for i, points in enumerate(points_lists): for point in points: tax.scatter([tuple(point)], color=colors[i], marker=markers[i]) tax.annotate("".join(map(str, point)), tuple(point), color=colors[i]) tax.gridlines(multiple=1.) ## Boundary and Gridlines scale = 40 figure, ternary_ax = ternary.figure(scale=scale)
nutau=[] for i in range(1000): nue.append(NUE[i]/N) numu.append(NUMU[i]/N) nutau.append(NUTAU[i]/N) #p.title(r"$(\nu_e,\nu_\mu,\nu_\tau)=(\frac{1}{2},\frac{1}{2},0)$",fontsize=15) #p.xlabel("probability") #p.ylabel(r"$\nu_e,\nu_\mu,\nu_\tau$") #p.step(P1,nue,label=r"$\nu_e$") #p.step(P1,numu,label=r"$\nu_\mu$") #p.step(P1,nutau,label=r"$\nu_\tau$") #p.legend() """ternary plot/triangular plot configuration/settings""" figure, d=t.figure(scale=1) d.boundary(linewidth=2) d.gridlines(multiple=0.1,color="blue",linewidth=0.8) #d.gridlines(multiple=0.02,color="green",linewidth=0.2) d.set_title(r"source flavour composition $\nu_e,\nu_\mu,\nu_\tau$",fontsize=20) d.left_axis_label(r"$\nu_\tau$",fontsize=20,offset=0.12) d.right_axis_label(r"$\nu_\mu$",fontsize=20,offset=-0.01) d.bottom_axis_label(r"$\nu_e$",fontsize=20,offset=0.01) d._redraw_labels() """data points""" point1=[(0.3980599331366308,0.3112164005027349,0.2907236663606344)] point2=[(0.55214511226237,0.24397475401089158,0.20388013372673847)] point3=[(0.34669820676138435,0.3336302826666826,0.31967151057193305)]
# full_filename = os.path.join(filename) # data = dict() # handle = open(full_filename) # for line in handle: # line = line.strip() # i, j, k, v = line.split(' ') # data[(float(i), float(j), float(k))] = float(v) # return data #data1 = load_sample_heatmap_data1() #data2 = load_sample_heatmap_data2() #data3 = load_sample_heatmap_data3() #data4 = load_sample_heatmap_data4() """heatmap""" figure, d=t.figure(scale=grid) d.boundary(linewidth=2) d.gridlines(multiple=0.1,color="blue",linewidth=0.8) d.set_title(r"source flavour composition $(\nu_e,\nu_\mu,\nu_\tau)=(\frac{1}{2},\frac{1}{2},0)$",fontsize=20) d.left_axis_label(r"$\nu_\tau$",offset=0.12) d.right_axis_label(r"$\nu_\mu$",offset=0.1) d.bottom_axis_label(r"$\nu_e$",offset=0) #d._redraw_labels() d.ticks(axis='brl',multiple=0.1) p.axis('off') #d.heatmap(data1,style="triangular") #d.boundary() #d.heatmap(data2,style="triangular") #d.heatmap(data3,style="hexagonal",cmap='Blues') #d.heatmap(data4,style="triangular",cmap='viridis') #d.resize_drawing_canvas(scale=1.15)
def dist(x,L): constt=(psat_bar/P)-1 dxdl= np.zeros_like(x) dxdl= np.dot(np.diag(constt),x/L) return dxdl #specifying initial conditions x0= np.array(x0) x0= np.reshape(x0,(len(x0),)) L_initial= conditions.iloc[0,2] #inital qty L_final= conditions.iloc[0,3] # final qty L= np.linspace(L_initial,L_final, 10) #integrate differnetial equations x= sci.odeint(dist,x0,L) print x #plotting ternary diagram figure,tax=ternary.figure(scale=1.0) tax.boundary() tax.gridlines(multiple=10, color="black") tax.left_axis_label("A component", fontsize=10) tax.right_axis_label("C component", fontsize=10) tax.bottom_axis_label("B component", fontsize=20) tax.set_title("Plotting of residue curve", fontsize=20) tax.plot(x) tax.show()
import ternary ## Boundary and Gridlines scale = 9 figure, tax = ternary.figure(scale=scale) tax.ax.axis("off") figure.set_facecolor('w') # Draw Boundary and Gridlines tax.boundary(linewidth=1.0) tax.gridlines(color="black", multiple=1, linewidth=0.5,ls='-') # Set Axis labels and Title fontsize = 15 tax.left_axis_label("Barleygrow", fontsize=fontsize, offset=0.12) tax.right_axis_label("Beans", fontsize=fontsize, offset=0.12) tax.bottom_axis_label("Oats", fontsize=fontsize, offset=0.025) # Set ticks tax.ticks(axis='blr', linewidth=1,multiple=1) # Scatter some points points = [(2,3,5),(3,6,1),(5,4,1),(3,4,3),(2,2,6)] c = [90,20,30,10,64] cb_kwargs = {"shrink" : 0.6, "orientation" : "horizontal", "fraction" : 0.1, "pad" : 0.05,
if __name__ == '__main__': N = 40 mu = 3./2. * 1./N m = [[1, 2], [2, 1]] fitness_landscape = linear_fitness_landscape(m, normalize=False) incentive = replicator(fitness_landscape) death_probabilities = even_death(N) edges = variable_population_transitions( N, fitness_landscape, death_probabilities, incentive=incentive, mu=mu) s = stationary_distribution(edges, iterations=10000) # Print out the states with the highest stationary probabilities vs = [(v, k) for (k, v) in s.items()] vs.sort(reverse=True) print(vs[:10]) # Plot the stationary distribution and expected divergence figure, tax = ternary.figure(scale=N) tax.heatmap(s) d2 = expected_divergence(edges, q_d=0) d = dict() for k, v in d2.items(): d[k] = math.sqrt(v) figure, tax = ternary.figure(scale=N) tax.heatmap(d) pyplot.show()
continue return -1.*s def random_points(num_points=25, scale=40): points = [] for i in range(num_points): x = random.randint(1, scale) y = random.randint(0, scale - x) z = scale - x - y points.append((x,y,z)) return points if __name__ == '__main__': ## Boundary and Gridlines scale = 40 figure, ternary_ax = ternary.figure(scale=scale) left_kwargs = {'color': 'blue'} right_kwargs = {'color': 'red'} # Draw Boundary and Gridlines ternary_ax.boundary(color="black", linewidth=2.0) ternary_ax.gridlines(color="blue", multiple=5, left_kwargs=left_kwargs, right_kwargs=right_kwargs) # Draw Boundary and Gridlines ternary_ax.boundary(color="black", linewidth=2.0) ternary_ax.gridlines(color="blue", multiple=5) # Set Axis labels and Title fontsize = 20