def plot_series(self, variables, ax=None, norm=False, add_labels=True, labels_xvals=None, use_true_times=True): """Plot particular variables' values over time Parameters __________ variables - iterable; the names of the variable whose values we want to plot ax - the matplotlib axes on which to plot norm - boolean; whether or not to normalise the time series by dividing through by the max add_labels - boolean; whether to label the variables when plotting labels_xvals - the positions along the x-axis at which to place the variables' labels (if using). If set to None, labels will be placed at regular intervals along x-axis. use_true_times - whether to use the 'actual' times or offset the times so that they start at zero """ if ax is None: ax = plt.gca() times = self.true_times if use_true_times else self.times for variable in variables: y = normed(self.series(variable)) if norm else self.series(variable) ax.plot(times, y, label=variable) if add_labels: if not labels_xvals: # Add evenly-spaced labels labels_interval = len(times) // (len(variables) + 1) labels_xvals = [times[labels_interval * (i + 1)] for i in range(len(variables))] labelLines(ax.get_lines(), zorder=2.5, xvals=labels_xvals)
def test_labels_range(): x = np.linspace(0, 1) plt.plot(x, np.sin(x), label='$\sin x$') plt.plot(x, np.cos(x), label='$\cos x$') labelLines(plt.gca().get_lines(), xvals=(0, .5))
def Initialize_Intrinsic_DefectsDiagram_Plot(self): # Plot defect formation energy of each intrinsic defect for intrinsic_defect in self.intrinsic_defects_enthalpy_data.keys(): defect_label = r"$" + intrinsic_defect.split( "_")[0] + "_{" + intrinsic_defect.split("_")[-1] + "}$" self.intrinsic_defect_plots[ intrinsic_defect], = self.defects_diagram_plot_drawing.plot( self.fermi_energy_array - self.EVBM, self.intrinsic_defects_enthalpy_data[intrinsic_defect], label=defect_label) # Create label for each defect labelLines(list(self.intrinsic_defect_plots.values()), align=False, xvals=np.linspace( 0.0, self.ECBM - self.EVBM, len(self.intrinsic_defect_plots.keys()) + 2)[1:len(self.intrinsic_defect_plots.keys()) + 1], fontsize=10, bbox=dict(facecolor='white', alpha=0.8, edgecolor='white', pad=0.5)) # Draw defects diagram canvas self.defects_diagram_plot_canvas.draw()
def graphAverageMessagesPerMonth(): """ Create a line graph of every user's average messages sent per month and save to output pdf """ currentFigure = plt.figure() averageMessagesPerMonth = plt.subplot() for user in userDict: userName = userDict[user].getFirstName() userMonthActivity = userDict[user].getAveragedMonthActivity() currentPlot = averageMessagesPerMonth.plot(list(range(0, 12)), userMonthActivity, label=userName) if totalUsers <= bigGraphThreshold: labelLines(plt.gca().get_lines()) averageMessagesPerMonth.set_title("Average Messages Sent per Month") averageMessagesPerMonth.set_xticks(np.arange(12)) averageMessagesPerMonth.set_xticklabels(months) else: averageMessagesPerMonth.legend() averageMessagesPerMonth.set_title("Average Messages Sent per Month", size=20) averageMessagesPerMonth.set_xticks(np.arange(12)) averageMessagesPerMonth.set_xticklabels(months, fontsize=18) averageMessagesPerMonth.set_ylabel("Messages Sent") averageMessagesPerMonth.set_xlabel("Users") currentFigure.autofmt_xdate() pdf.savefig(currentFigure)
def graphAverageMessagesPerHour(): """ Create a line graph of every user's average messages sent per hour """ currentFigure = plt.figure() averageMessagesPerHour = plt.subplot() for user in userDict: userName = userDict[user].getFirstName() userHourActivity = userDict[user].getAveragedHourActivity() currentPlot = averageMessagesPerHour.plot(list(range(0, 24)), userHourActivity, label=userName) if totalUsers <= bigGraphThreshold: labelLines(plt.gca().get_lines()) averageMessagesPerHour.set_title( "Average Messages Sent per Hour of Day") averageMessagesPerHour.set_xticks(np.arange(24)) averageMessagesPerHour.set_xticklabels(range(0, 24)) else: averageMessagesPerHour.legend() averageMessagesPerHour.set_title( "Average Messages Sent per Hour of Day", size=20) averageMessagesPerHour.set_xticks(np.arange(24)) averageMessagesPerHour.set_xticklabels(list(range(0, 24)), fontsize=18) averageMessagesPerHour.set_ylabel("Messages Sent") averageMessagesPerHour.set_xlabel("Hour of Day") currentFigure.autofmt_xdate() pdf.savefig(currentFigure)
def gen_line(dct, label, cat, file_label): try: os.mkdir( f'{cat.replace(" ", "_").replace("&", "_")}_Cumulative_Line_Charts' ) except FileExistsError: pass quarters = ['Q32019'] + list(model.quarters) NUM_COLORS = len(dct) cm = plt.get_cmap('gist_rainbow') fig = plt.figure() ax = fig.add_subplot(111) ax.set_prop_cycle('color', [cm(1. * i / NUM_COLORS) for i in range(NUM_COLORS)]) plt.xticks(numpy.arange(5), quarters) # plt.ylim(-0.4, 0.6) for comp in dct: plt.plot(range(5), [0] + [ sum(list(dct[comp].values())[:(i + 1)]) for i in range(len(model.quarters)) ], label=comp) plt.xlabel('Quarter') ax.axhline(color='black') plt.ylabel(f'Cumulative {label}') plt.title(f'Cumulative {label} for {cat}') # plt.tight_layout() try: labelLines(plt.gca().get_lines()) except: pass plt.savefig( f'{cat.replace(" ", "_").replace("&", "_")}_Cumulative_Line_Charts/{cat.replace(" ", "_").replace("&", "_")}_{file_label}_cum.png', bbox_inches='tight')
def test_fatality_prob_curves(self): """ Recreate the figure in Dalamagkidis et al. """ alpha = 1e6 beta = 34 p_s = np.linspace(0, 1, 11) ke = np.logspace(0, 15) p_f = [prob_fatality(ke, alpha, beta, p) for p in p_s] fig, ax = mpl.subplots(1, 1, figsize=(8, 5)) ax.set_xlim(1, 1e14) ax.set_ylim(0, 1.1) for idx, p in enumerate(p_f): ax.plot(ke, p, label=f'$p_s={p_s[idx]:1g}$') x_pos = np.logspace(1.6, 11.6, 11) labelLines(ax.get_lines(), xvals=x_pos) ax.set_xlabel('Impact Kinetic Energy [J]') ax.set_ylabel('Probability of Fatality') ax.set_xscale('symlog') ax.set_title( f'Probability of Fatality - Dalamagkidis Model\n $\\alpha={alpha:3g}$, $\\beta={beta:3g}$' ) fig.show()
def test_align(): x = np.linspace(0, 2 * np.pi) y = np.sin(x) lines = plt.plot(x, y, label='$sin(x)$') labelLines(lines, align=False)
def test_labels_range(): x = np.linspace(0, 1) plt.plot(x, np.sin(x), label=r"$\sin x$") plt.plot(x, np.cos(x), label=r"$\cos x$") labelLines(plt.gca().get_lines(), xvals=(0, 0.5)) return plt.gcf()
def test_non_uniform_and_negative_spacing(): x = [1, -2, -3, 2, -4, -3] plt.plot(x, [1, 2, 3, 4, 2, 1], '.-', label='apples') plt.plot(x, [6, 5, 4, 2, 5, 5], 'o-', label='banana') ax = plt.gca() labelLines(ax.get_lines()) return plt.gcf()
def test_non_uniform_and_negative_spacing(): x = [1, -2, -3, 2, -4, -3] plt.plot(x, [1, 2, 3, 4, 2, 1], ".-", label="apples") plt.plot(x, [6, 5, 4, 2, 5, 5], "o-", label="banana") ax = plt.gca() labelLines(ax.get_lines()) return plt.gcf()
def test_align(): x = np.linspace(0, 2*np.pi) y = np.sin(x) lines = plt.plot(x, y, label=r'$\sin(x)$') labelLines(lines, align=False) return plt.gcf()
def plot_errors_combined(errors, labels): for error_vals, label in zip(errors, labels): plt.plot(error_vals, label=label) plt.xlabel("Time-step") plt.ylabel("Posterior Estimation Error") labelLines(plt.gca().get_lines(), zorder=2.5) plt.show()
def test_polar(): t = np.linspace(0, 2 * np.pi, num=128) plt.plot(np.cos(t), np.sin(t), label='$1/1$') plt.plot(np.cos(t), np.sin(2 * t), label='$1/2$') plt.plot(np.cos(3 * t), np.sin(t), label='$3/1$') ax = plt.gca() labelLines(ax.get_lines()) return plt.gcf()
def test_linspace(): plt.clf() x = np.linspace(0, 1) K = [1, 2, 4] for k in K: plt.plot(x, np.sin(k * x), label='$f(x)=sin(%s x)$' % k) labelLines(plt.gca().get_lines(), zorder=2.5) plt.xlabel('$x$') plt.ylabel('$f(x)$')
def test_dateaxis_naive(): dates = [datetime(2018, 11, 1), datetime(2018, 11, 2), datetime(2018, 11, 3)] plt.plot(dates, [0, 5, 3], label='apples') plt.plot(dates, [3, 6, 2], label='banana') ax = plt.gca() ax.xaxis.set_major_locator(DayLocator()) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) labelLines(ax.get_lines()) return plt.gcf()
def test_linspace(): plt.clf() x = np.linspace(0, 1) K = [1, 2, 4] for k in K: plt.plot(x, np.sin(k * x), label=r"$f(x)=\sin(%s x)$" % k) labelLines(plt.gca().get_lines(), zorder=2.5) plt.xlabel("$x$") plt.ylabel("$f(x)$") return plt.gcf()
def test_xlogspace(): plt.clf() x = np.linspace(0, 1) K = [1, 2, 4] for k in K: plt.plot(10**x, k * x, label='$f(x)=%s x$' % k) plt.xscale('log') labelLines(plt.gca().get_lines(), zorder=2.5) plt.xlabel('$x$') plt.ylabel('$f(x)$')
def test_dateaxis_advanced(): dates = [datetime(2018, 11, 1, tzinfo=UTC), datetime(2018, 11, 2, tzinfo=UTC), datetime(2018, 11, 5, tzinfo=UTC), datetime(2018, 11, 3, tzinfo=UTC)] plt.plot(dates, [0, 5, 3, 0], label='apples') plt.plot(dates, [3, 6, 2, 1], label='banana') ax = plt.gca() ax.xaxis.set_major_locator(DayLocator()) ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) labelLines(ax.get_lines()) return plt.gcf()
def quantile_chg_plot(df1, df2, col1, col2, w1=None, w2=None, q=None, label1="Base", label2="Reform", title="Change in disposable income percentiles", currency="USD"): """Create plot with one line per quantile boundary between base and reform. :param df1: DataFrame with first set of values. :param df2: DataFrame with second set of values. :param col1: Name of columns with values in df1. :param col2: Name of columns with values in df2. :param w1: Name of weight column in df1. :param w2: Name of weight column in df2. :param q: Quantiles. Defaults to decile boundaries. :param label1: Label for left side of x-axis. Defaults to 'Base'. :param label2: Label for right side of x-axis. Defaults to 'Reform'. :returns: Axis. """ # Calculate the q default because it's later used for defining a color # palette. if q is None: q = np.arange(0.1, 1, 0.1) # Calculate weighted quantiles. df = mdf.quantile_chg(df1, df2, col1, col2, w1, w2, q) # Make shades of green, removing the lightest 10 shades. with sns.color_palette(sns.color_palette("Greens", q.size + 11)[11:]): ax = df.plot() # Label the start and end points. plt.xticks([0, 1], [label1, label2]) # Label the lines instead of using a legend. ax.get_legend().remove() # Move line labels closer to the center. ll.labelLines(plt.gca().get_lines(), xvals=(0.1, 0.9)) # Formatting. plt.title(title) plt.ylim(0, None) ax.grid(color=mdf.GRID_COLOR, axis="y") formatter = mdf.currency_format(currency) ax.yaxis.set_major_formatter(formatter) ax.yaxis.set_minor_formatter(formatter) sns.despine(left=True, bottom=True) ax.axhline(0, color="lightgray", zorder=-1) # Looks better narrower. plt.gcf().set_size_inches(4, 6) return ax
def Update_Intrinsic_DefectsDiagram_Plot(self): # Update defect formation energy of each intrinsic defect for intrinsic_defect in self.intrinsic_defects_enthalpy_data.keys(): self.intrinsic_defect_plots[intrinsic_defect].set_ydata(self.intrinsic_defects_enthalpy_data[intrinsic_defect]) # Remove labels before redrawing them at new positions self.ternary_defects_diagram_plot_drawing.texts.clear() labelLines(list(self.intrinsic_defect_plots.values()), align = False, xvals = np.linspace(0.0, self.ECBM-self.EVBM, len(self.intrinsic_defect_plots.keys())+2)[1:len(self.intrinsic_defect_plots.keys())+1], fontsize = 10, bbox = dict(facecolor = 'white', alpha = 0.8, edgecolor = 'white', pad = 0.5)) # Draw defects diagram canvas self.ternary_defects_diagram_plot_canvas.draw()
def test_ylogspace(): plt.clf() x = np.linspace(0, 1) K = [1, 2, 4] for k in K: plt.plot(x, np.exp(k * x), label='$f(x)=exp(%s x)$' % k) plt.yscale('log') labelLines(plt.gca().get_lines(), zorder=2.5) plt.xlabel('$x$') plt.ylabel('$f(x)$')
def versus(gwaff, save: bool = False): today = date.today() with open("config.yml", "r") as file: config = safe_load(file) files = [] if config["darkmode"]: plt.style.use("dark_background") plt.figure(figsize=(14, 7)) if config["versus"] == None: exit(1) for user in gwaff: if int(user) in config["versus"]: y = [0] x = [] total_xp_ = list(gwaff[user]["total_xp"])[-10:] total_xp = [] for i in total_xp_: total_xp.append(gwaff[user]["total_xp"][i]) for i in zip(total_xp, total_xp[1:]): y.append(abs(i[0] - i[1])) f = 0 while f < len(list(total_xp)): x.append(f) f += 1 plt.plot(x, y, label=gwaff[user]["name"].split("#")[0]) try: labelLines(plt.gca().get_lines(), align=True) except IndexError: print("labelLines failed") plt.legend(bbox_to_anchor=(1, 1)) plt.xlabel( f"started at {list(gwaff[next(iter(gwaff))]['total_xp'])[-10:][0].split(' ')[0]}" f"{config['bottom_message']}" f" {today.strftime('%B %d, %Y')}") plt.ylabel("gain") plt.title(f"versus") plt.grid(axis="y") plt.tight_layout() if save: plt.savefig(f"images/plot_versus.png") files.append(f"images/plot_versus.png") else: plt.show() plt.close() plt.figure(figsize=(14, 7)) q = 0 return files
def matelem_vs_paramvals( specdata: "SpectrumData", select_elems: Union[int, List[Tuple[int, int]]] = 4, mode: str = "abs", **kwargs ) -> Tuple[Figure, Axes]: """Generates a simple plot of matrix elements as a function of one parameter. The individual points correspond to the a provided array of parameter values. Parameters ---------- specdata: object includes parameter name, values, and matrix elements select_elems: either maximum index of desired matrix elements, or list [(i1, i2), (i3, i4), ...] of index tuples for specific desired matrix elements mode: choice of processing function to be applied to data (default value = 'abs') **kwargs: standard plotting option (see separate documentation) Returns ------- matplotlib objects for further editing """ fig, axes = kwargs.get("fig_ax") or plt.subplots() x = specdata.param_vals modefunction = constants.MODE_FUNC_DICT[mode] if isinstance(select_elems, int): index_pairs = [ (row, col) for row in range(select_elems) for col in range(row + 1) ] else: index_pairs = select_elems for (row, col) in index_pairs: y = modefunction(specdata.matrixelem_table[:, row, col]) axes.plot( x, y, label=str(row) + "," + str(col), **_extract_kwargs_options(kwargs, "plot") ) if _LABELLINES_ENABLED: labelLines(axes.get_lines(), zorder=1.5) else: axes.legend(loc="center left", bbox_to_anchor=(1, 0.5)) _process_options(fig, axes, opts=defaults.matelem_vs_paramvals(specdata), **kwargs) return fig, axes
def test_xlogspace(): plt.clf() x = np.linspace(0, 1) K = [1, 2, 4] for k in K: plt.plot(10**x, k * x, label=r"$f(x)=%s x$" % k) plt.xscale("log") labelLines(plt.gca().get_lines(), zorder=2.5) plt.xlabel("$x$") plt.ylabel("$f(x)$") return plt.gcf()
def test_xylogspace(): plt.clf() x = np.geomspace(1e-1, 1e1) K = np.arange(-5, 5, 2) for k in K: plt.plot(x, x**k, label='$f(x)=x^{%s}$' % k) plt.xscale('log') plt.yscale('log') labelLines(plt.gca().get_lines(), zorder=2.5) plt.xlabel('$x$') plt.ylabel('$f(x)$')
def test_errorbar(): x = np.linspace(0, 1, 20) y = x**0.5 dy = x plt.errorbar(x, y, yerr=dy, label=r'$\sqrt{x}\pm x$') y = x**3 dy = x plt.errorbar(x, y, yerr=dy, label=r'$x^3\pm x$') ax = plt.gca() labelLines(ax.get_lines()) return plt.gcf()
def test_xylogspace(): plt.clf() x = np.geomspace(1e-1, 1e1) K = np.arange(-5, 5, 2) for k in K: plt.plot(x, x**k, label=r"$f(x)=x^{%s}$" % k) plt.xscale("log") plt.yscale("log") labelLines(plt.gca().get_lines(), zorder=2.5) plt.xlabel("$x$") plt.ylabel("$f(x)$") return plt.gcf()
def visualise(df, outfile='out.svg'): title = f'Chances for winning the presidency for major candidates, given that they win the primary ({WINDOW} rolling mean)' title = '\n'.join(wrap(title, 60)) plt.style.use('fivethirtyeight') plt.rcParams['svg.fonttype'] = 'none' fig, ax = plt.subplots(figsize=(13.9, 9.84)) df.plot(title=title, ax=ax, sort_columns=True) labelLines(plt.gca().get_lines(), align=False, xvals=repeat(df.index[-1]), clip_on=False, horizontalalignment='left', backgroundcolor='#FFFFFF00') plt.axhline(0.5, color='lightgray', linestyle='--') # Mark 50% line ax.set_yticklabels(['{:,.0%}'.format(x) for x in ax.get_yticks()]) ax.xaxis.label.set_visible(False) ax.xaxis.set_major_locator(mdates.WeekdayLocator(0)) fig.tight_layout() props = dict(boxstyle='round', facecolor='white', alpha=0.5) textstr = '\n'.join([ 'How this is calculated:', BULLET + 'https://en.wikipedia.org/wiki/Conditional_probability', 'Data sources:', BULLET + urlPrimary, BULLET + urlFinal, 'Source code:', BULLET + 'https://github.com/Synthetica9/ElectionOdds' ]) print(textstr) ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14, verticalalignment='top', bbox=props) plt.grid(axis='y') plt.savefig(outfile) plt.close()
def data_vs_paramvals(xdata: np.ndarray, ydata: np.ndarray, label_list: Union[List[str], List[int]] = None, **kwargs) -> Tuple[Figure, Axes]: """Plot of a set of yadata vs xdata. The individual points correspond to the a provided array of parameter values. Parameters ---------- xdata, ydata: must have compatible shapes for matplotlib.pyplot.plot label_list: list of labels associated with the individual curves to be plotted **kwargs: standard plotting option (see separate documentation) Returns ------- matplotlib objects for further editing """ fig, axes = kwargs.get("fig_ax") or plt.subplots() if label_list is None: axes.plot(xdata, ydata, **_extract_kwargs_options(kwargs, "plot")) else: for idx, ydataset in enumerate(ydata.T): axes.plot(xdata, ydataset, label=label_list[idx], **_extract_kwargs_options(kwargs, "plot")) if _LABELLINES_ENABLED: try: labelLines(axes.get_lines(), zorder=2.0) except Exception: pass else: axes.legend( bbox_to_anchor=(1.04, 0.5), loc="center left", borderaxespad=0, frameon=False, ) # legend(loc="center left", bbox_to_anchor=(1, 0.5)) _process_options(fig, axes, **kwargs) return fig, axes
colors = [imf.color_from_mass(m) for m in hmasses] pl.scatter(10**htems, hmasses, c=colors, s=(10**hlums)**0.25*45) # overlay star age horizontal lines lines = [] for age in (6.5, 7, 8, 10): L, = pl.plot([10**tems.min(), (10**htems.max())], [agemass[age]]*2, linestyle='--', color='k', label="$10^{{{0}}}$ yr".format(age)) lines.append(L) labelLines(lines) pl.xlabel("Temperature") pl.ylabel("Mass") pl.tight_layout() pl.savefig("mass_lum_diagram.svg")#, bbox_inches='tight') # HR diagram (temperature-luminosity) pl.figure(3, figsize=(8,8)).clf() colors = [imf.color_from_mass(m) for m in subtbl['Mass']] #pl.gca().set_xscale('log') pl.gca().set_yscale('log') pl.scatter(10**subtbl['logTe'], 10**subtbl['logL'], c=colors,