示例#1
0
 def plot_trajectory(cls):
     # see: https://aatishb.com/covidtrends/
     df = cls.data
     sel_countries = chart_trajectory_countries
     aff = df[df["entity"].isin(sel_countries)
              & (df["confirmed"] > chart_min_pop)]
     traj = aff[["entity", "date", "confirmed"]].copy()
     traj["increase"] = aff["confirmed"] - UnifiedDataModel.date_shifted_by(
         aff, "confirmed", days(7)).fillna(0)
     fig, axs = pk.new_regular()
     more_cyclers(axs)
     sel_countries_sorted = list(
         sorted(sel_countries,
                key=lambda c: traj[traj["entity"] == c]["increase"].max(),
                reverse=True))
     for c in sel_countries_sorted:
         cdata = traj[traj["entity"] == c]
         xydata = cdata[["confirmed", "increase"
                         ]].sort_values(by="confirmed").to_numpy()
         p = axs.plot(*xydata.T, label=c)
         axs.scatter(*xydata[-1].T, label="_", c=pk.get_object_facecolor(p))
     axs.set_xscale("log")
     axs.set_yscale("log")
     pk.set_grid(axs)
     axs.legend()
     axs.set_xlabel("Total confirmed cases")
     axs.set_ylabel("New confirmed cases / 7 day period")
     axs.xaxis.set_major_formatter(mticker.EngFormatter())
     axs.yaxis.set_major_formatter(mticker.EngFormatter())
     axs.annotate("Last data: " + str(traj["date"].max()),
                  xy=(0.5, 0),
                  xycoords="figure fraction",
                  ha="center",
                  va="bottom")
     pk.finalize(fig, f"trajectory.png")
示例#2
0
def draw_box_plot():
    # Prepare data for box plots
    df_box = clean_df.copy()
    df_box.reset_index(inplace=True)
    df_box['year'] = [d.year for d in df_box.date]
    df_box['month'] = [d.strftime('%b') for d in df_box.date]

    # Draw box plots (using Seaborn)
    # Create a figure with 2 axes
    fig, (ax1, ax2) = plt.subplots(ncols=2,
                                   figsize=(10, 8),
                                   constrained_layout=True,
                                   dpi=200)

    # First Axes
    sns.boxplot(data=df_box, ax=ax1, x='year', y='value')
    ax1.yaxis.set_major_formatter(
        ticker.EngFormatter())  #This line could be better
    ax1.set(ylim=(20000, 200000))
    ax1.set_xlabel('Year')
    ax1.set_ylabel('Page Views')
    ax1.set_title('Year-wise Box Plot(Trend)')

    # Second Axes
    sns.boxplot(data=df_box, ax=ax2, x='month', y='value')
    ax2.yaxis.set_major_formatter(ticker.EngFormatter())
    ax2.set(ylim=(20000, 200000))
    ax2.set_xlabel('Month')
    ax2.set_ylabel('Page Views')
    ax2.set_title('Month-wise Box Plot(Seasonality)')

    # Save image and return fig
    fig.savefig('box_plot.png')
    return fig
示例#3
0
    def plot_Omega_and_Delta(self, ax, plot_title: bool = True):
        """
        Plots Omega and Delta as a function of time.
        Includes overlap with GHZ state if `self.solve_result` is not None (self.solve has been called).
        :return:
        """
        ax.xaxis.set_major_formatter(ticker.EngFormatter('s'))
        plt.xlabel('Time')

        ax.plot(self.t_list, [self.Omega(t) for t in self.t_list],
                label=r"$\Omega{}$",
                lw=3,
                alpha=0.8)
        ax.plot(self.t_list, [self.Delta(t) for t in self.t_list],
                label=r"$\Delta{}$",
                lw=3,
                alpha=0.8)
        ax.yaxis.set_major_formatter(ticker.EngFormatter('Hz'))
        ax.locator_params(nbins=4, axis='y')
        ax.locator_params(nbins=5, axis='x')

        ax.legend()
        if plot_title:
            ax.set_title("Control parameters")
        delta = (self.t_list.max() - self.t_list.min()) * 0.01
        ax.set_xlim((self.t_list.min() - delta, self.t_list.max() + delta))
def sci_labels(ax,
               decimals=2,
               x=True,
               y=True,
               z=False,
               unit='',
               y_unit: str = None,
               rotation=30):
    if decimals < 2:
        print('Warning, pyplot may round labels')
    formatter = tck.EngFormatter(places=decimals,
                                 sep=u"\N{THIN SPACE}",
                                 unit=unit)
    if x:
        ax.xaxis.set_major_formatter(formatter)
        plt.xticks(rotation=rotation)
    if z:
        # 3D plot
        ax.zaxis.set_major_formatter(formatter)
    if y:
        plt.yticks(rotation=rotation)
        if y_unit is not None:
            formatter = tck.EngFormatter(places=decimals,
                                         sep=u"\N{THIN SPACE}",
                                         unit=y_unit)
        ax.yaxis.set_major_formatter(formatter)
示例#5
0
def config_axis(ax=None,
                x_lim=None,
                y_lim=None,
                X_0=None,
                Y_0=None,
                grd=True,
                minorgrd=False,
                mult_x=0.2,
                mult_y=0.2,
                Eng=True):
    if (X_0 != None):
        ax.xaxis.set_major_locator(ticker.MultipleLocator(mult_x * X_0))
        ax.xaxis.set_minor_locator(ticker.MultipleLocator((mult_x / 5) * X_0))
    if (Eng):
        ax.xaxis.set_major_formatter(ticker.EngFormatter())
        ax.yaxis.set_major_formatter(ticker.EngFormatter())
    if (Y_0 != None):
        ax.yaxis.set_major_locator(ticker.MultipleLocator(mult_y * Y_0))
        ax.yaxis.set_minor_locator(ticker.MultipleLocator(mult_y / 5 * Y_0))
    if (grd == True):
        ax.grid(b=True, which='major', axis='both')
    else:
        ax.grid(b=False, which='major', axis='both')
    if (minorgrd == True):
        ax.grid(b=True, which='minor', axis='both')
    else:
        ax.grid(b=False, which='minor', axis='both')

    if (x_lim != None):
        ax.set_xlim(x_lim)
    if (y_lim != None):
        ax.set_ylim(y_lim)
    return ax
示例#6
0
def plot_bode(outfile):
    plt.clf()
    printall(ns.cmd("alter c6 100u"))
    #printall(ns.cmd("alter v1 3"))
    #printall(ns.cmd("alter v2 3"))

    gains = [500**(1 / n) for n in range(3, 0, -1)]
    impedances = [1000, 10 * 1000, 100 * 1000, 1000 * 1000, 10 * 1000 * 1000]
    currents_mA = [0] + list(my_logspace(0.0001, 10, 5 if DRAFT_MODE else 16))

    _, plots = plt.subplots(
        len(gains),
        len(impedances) + 1,
        gridspec_kw={'width_ratios': [3] * len(impedances) + [1]})

    fmt_Hz = ticker.EngFormatter(unit='Hz')
    fmt_dB = ticker.EngFormatter(unit='dB')
    ohmfmt = ticker.EngFormatter(unit="Ω")

    for y, gain in enumerate(gains):
        for x, impedance_ohms in enumerate(impedances):
            update_amplifier(impedance_ohms, gain)
            plot_single_bode_family(plots[y][x], currents_mA)
            plots[y][x].set_ylim(10 * math.log10(gain / 500) - 55,
                                 10 * math.log10(gain / 500) + 5)
            plots[y][x].xaxis.set_major_formatter(fmt_Hz)
            plots[y][x].yaxis.set_major_formatter(fmt_dB)

            if x == 0:
                plots[y][x].text(0,
                                 0.5,
                                 'gain = %.1f×\n\n\n\n' % gain,
                                 fontsize=10,
                                 horizontalalignment='right',
                                 verticalalignment='center',
                                 transform=plots[y][x].transAxes,
                                 rotation='vertical')

            if y == 0:
                plots[y][x].text(0.5,
                                 1.0,
                                 'impedance = %s\n' %
                                 ohmfmt.format_data(impedance_ohms),
                                 fontsize=10,
                                 horizontalalignment='center',
                                 verticalalignment='baseline',
                                 transform=plots[y][x].transAxes)
            if y == len(gains) - 1:
                plots[y][x].set_xlabel("Frequency")

    for p in plots:
        p[-1].axis(False)

    fmt = ticker.EngFormatter(unit="A")
    make_legend([fmt.format_data(c / 1000) for c in currents_mA], plots[0][-1])

    plt.gcf().set_size_inches(20, 11)
    if outfile is not None:
        plt.savefig(outfile)
示例#7
0
def plot_detuning_energy_levels(s_qs: StaticQubitSystem,
                                crossings: np.ndarray,
                                ax: Axes,
                                highlighted_indices: Sequence[int] = (-1, )):
    if s_qs.Omega_zero_energies is None:
        s_qs.get_energies()

    crossings_range = crossings.max() - crossings.min()
    xlims = crossings_range * -0.1, crossings.max() * 1.1
    s_qs = StaticQubitSystem(s_qs.N,
                             s_qs.V,
                             s_qs.geometry,
                             Omega=0,
                             Delta=np.linspace(xlims[0], xlims[1], 20))
    s_qs.get_energies()

    g = states_quimb.get_ground_states(1)[0]
    for i, state in enumerate(s_qs.states):
        is_highlight_state = any(state is s_qs.states[i]
                                 for i in highlighted_indices)
        is_ground_state = all((_state == g).all() for _state in state)

        color = 'g' if is_ground_state else 'r' if is_highlight_state else 'grey'
        linewidth = 5 if is_ground_state or is_highlight_state else 1
        z_order = 2 if is_ground_state or is_highlight_state else 1
        energies = s_qs.Omega_zero_energies[:, i]
        ax.plot(s_qs.Delta,
                energies,
                color=color,
                alpha=0.6,
                lw=linewidth,
                zorder=z_order,
                label=states_quimb.get_label_from_state(state),
                picker=3)

    def on_pick(event):
        line = event.artist
        print(f'Clicked on: {line.get_label()}')

    plt.gcf().canvas.mpl_connect('pick_event', on_pick)

    ax.grid()
    scaled_xaxis_ticker = ticker.EngFormatter(unit="Hz")
    scaled_yaxis_ticker = ticker.EngFormatter(unit="Hz")
    ax.xaxis.set_major_formatter(scaled_xaxis_ticker)
    ax.yaxis.set_major_formatter(scaled_yaxis_ticker)
    ax.locator_params(nbins=4)

    # plt.title(rf"Energy spectrum with $N = {self.N}$, $V = {self.V:0.2e}$, $\Omega = {self.Omega:0.2e}$")
    _m, _s = f"{s_qs.V:0.2e}".split('e')
    V_text = rf"{_m:s} \times 10^{{{int(_s):d}}}"
    plt.title(rf"Energy spectrum with $N = {s_qs.N}$, $V = {V_text:s}$ Hz")
    plt.xlabel(r"Detuning $\Delta$")
    plt.ylabel("Eigenenergy")

    plt.xlim(xlims)
    plt.tight_layout()
示例#8
0
 def _add_std_figure_formatting(self, x_unit, y_unit):
     # pylint: disable=no-self-use
     x_formatter = ticker.EngFormatter(unit=x_unit)
     y_formatter = ticker.EngFormatter(unit=y_unit)
     x_formatter.ENG_PREFIXES[-6] = 'u'
     y_formatter.ENG_PREFIXES[-6] = 'u'
     ax = plt.gca()
     ax.xaxis.set_major_formatter(x_formatter)
     ax.yaxis.set_major_formatter(y_formatter)
     plt.grid('on', which='both')
示例#9
0
def test_engformatter_usetex_useMathText():
    fig, ax = plt.subplots()
    ax.plot([0, 500, 1000], [0, 500, 1000])
    ax.set_xticks([0, 500, 1000])
    for formatter in (mticker.EngFormatter(usetex=True),
                      mticker.EngFormatter(useMathText=True)):
        ax.xaxis.set_major_formatter(formatter)
        fig.canvas.draw()
        x_tick_label_text = [labl.get_text() for labl in ax.get_xticklabels()]
        # Checking if the dollar `$` signs have been inserted around numbers
        # in tick labels.
        assert x_tick_label_text == ['$0$', '$500$', '$1$ k']
示例#10
0
文件: viz.py 项目: pqwy/unmark
def plot_trendlines(mx, ax=None, unit=None, **prop):

    ax = ax or plt.gca()
    color = prop.pop('color', None)

    xs, ys = mx[:, 0], mx[:, 1]
    yerr = (ys - mx[:, 2], mx[:, 3] - ys)

    ax.errorbar(xs, ys, yerr=yerr, fmt='-o', color=color)

    fmt = ticker.EngFormatter(unit=unit or "")
    ax.yaxis.set_major_formatter(fmt)
    ax.xaxis.set_major_formatter(ticker.EngFormatter())
示例#11
0
 def kreise_plot(entity_parent,
                 short,
                 *,
                 field="confirmed",
                 maxn: Optional[int] = 10,
                 stack=False,
                 order_total: Union[bool, int] = False):
     fig, axs = pk.new_regular()
     more_cyclers(axs)
     pv = pivoted(entity_parent, field, maxn, order_total)
     plot_dataframe(axs,
                    pv,
                    stacked=stack,
                    kind="bar" if stack else "line")
     axs.set_ylabel(field)
     axs.annotate("Last data update: " + str(pv.last_modified),
                  xy=(0.5, 0),
                  xycoords="figure fraction",
                  ha="center",
                  va="bottom")
     set_dateaxis(axs)
     pk.set_grid(axs)
     axs.set_ylim(0, )
     axs.yaxis.set_major_formatter(mticker.EngFormatter())
     pk.finalize(fig, f"local_{field}_{short}.png")
示例#12
0
def plot_basis_state_populations_3d(e_qs: EvolvingQubitSystem):
    if e_qs.solve_result is None:
        e_qs.solve()

    states = get_states(e_qs.N)

    times = []
    heights = []
    xs = []

    for i, _solve_result_state in enumerate(e_qs.solve_result.states):
        plt.ylim(0, 1)
        plt.grid(axis='y')

        solve_result_state_populations = np.abs(_solve_result_state.data.toarray().flatten()) ** 2
        for _x, state in enumerate(states):
            state_product_basis_index = get_product_basis_states_index(state)
            basis_state_population = solve_result_state_populations[state_product_basis_index]
            times.append(e_qs.solve_result.times[i])
            xs.append(_x)
            heights.append(basis_state_population)

    fig = plt.figure(figsize=(15, 8))
    ax = fig.add_subplot(111, projection="3d")
    dt = e_qs.solve_result.times[1] - e_qs.solve_result.times[0]
    ax.bar3d(xs, times, z=0, dx=0.8, dy=dt, dz=heights)
    labels = [get_label_from_state(state) for state in states]
    x = np.arange(len(labels))
    plt.xticks(x, labels)

    ax.yaxis.set_major_formatter(ticker.EngFormatter('s'))
    plt.ylabel('Time')
    plt.show()
示例#13
0
def plot_top(df, column, top_n=10):
    '''
    Plot % of top count values in a column in a Spark dataframe
    Parameters: 
        df (DataFrame): Spark dataframe to plot
        column   (str): Column name to plot
        top_n    (int): Quantity of top values
    '''

    column_top = df.groupBy(column).count().sort(
        f.desc('count')).limit(top_n).toPandas()
    column_top[column] = column_top[column].astype(str)  # safely display dates

    plt.figure(figsize=(5, 3))
    ax = seaborn.barplot(y=column, x='count', data=column_top)
    ax.set_xlim(0, df.count())
    ax.xaxis.set_major_formatter(
        ticker.EngFormatter())  # https://stackoverflow.com/a/53749220

    for p in ax.patches:  # https://link.medium.com/BNlbiicbjeb
        h = p.get_height()
        w = p.get_width()
        ax.text(x=w + 3, y=p.get_y() + h / 2, s=f'{w:.0f}', va='center')

    plt.show()
示例#14
0
def plotFourierData(freq, mag, axis=None, color='b', alpha=1.0):
    ax = axis

    if axis is None:
        fig = plt.figure(1337)
        fig.clf()
        fig.canvas.set_window_title("Non-Intrusive Load Monitoring - Frequency Spectrum - Felix Maass")

        ax = fig.add_subplot(111)

    ax.plot(freq, mag, color=color, alpha=alpha)

    ax.set_title("Frequency Spectrum")

    ax.set_xlabel('Frequency [Hz]')
    ax.get_xaxis().set_major_formatter(ticker.EngFormatter())
    ax.get_xaxis().set_minor_formatter(ticker.NullFormatter())

    ax.set_ylabel('Magnitude (log10)')
    ax.set_yscale('log')

    #######

    if axis is None:
        fig.tight_layout()
        plt.show()
示例#15
0
def plotIVCurve(chunk, axis=None):
    ax = axis

    if axis is None:
        fig = plt.figure(314)
        fig.clf()
        fig.canvas.set_window_title("Non-Intrusive Load Monitoring - Current-Voltage Characteristics - Felix Maass")

        ax = fig.add_subplot(111)

    ax.set_title("IV-Curve")
    ax.set_xlabel('Voltage [V]')
    ax.set_ylabel('Amperage [A]')

    ax.get_xaxis().set_major_formatter(ticker.EngFormatter())
    ax.get_xaxis().set_minor_formatter(ticker.NullFormatter())

    if np.max(np.abs(chunk['i'])) < 0.3:
        ax.set_ylim([-500,500])
        ax.set_autoscaley_on(False)
    else:
        ax.set_autoscaley_on(True)

    ax.plot(chunk['u'], chunk['i'], color='b')


    #######

    if axis is None:
        fig.tight_layout()
        plt.show()
示例#16
0
def plotPowerCurve(chunk, axis=None):
    ax = axis

    if axis is None:
        fig = plt.figure(271)
        fig.clf()
        fig.canvas.set_window_title("Non-Intrusive Load Monitoring - Power Characteristics - Felix Maass")

        ax = fig.add_subplot(111)


    ax.set_title("Power")
    ax.set_xlabel('Time [ms]')
    ax.set_ylabel('Power [VA / W / VAr]')

    ax.get_xaxis().set_major_formatter(ticker.EngFormatter())
    ax.get_xaxis().set_minor_formatter(ticker.NullFormatter())

    apparentPower   = chunk['u'] * chunk['i']

    phaseShift      = calculatePhaseShift(chunk)
    realPower       = apparentPower * cos(phaseShift)
    reactivePower   = apparentPower * sin(phaseShift)

    ax.plot(chunk['t'], apparentPower, color='r', label='Apparent')
    ax.plot(chunk['t'], realPower, color='g', label='Real')
    ax.plot(chunk['t'], reactivePower, color='b', label='Reactive')

    ax.legend()

    #######

    if axis is None:
        fig.tight_layout()
        plt.show()
示例#17
0
def plot_subword_growth():
    examples = load_gold_standard()
    unique_subwords = set()
    n_unique_subwords = list()
    for word in examples:
        unique_subwords = unique_subwords.union(word)
        n_unique_subwords.append(len(unique_subwords))
    fig, ax = plt.subplots(1, 1, figsize=(5, 4))
    sns.lineplot(range(len(n_unique_subwords)),
                 n_unique_subwords,
                 palette='dark')  # , c='b')
    plt.xlabel("Number of words")
    plt.ylabel("Unique subwords")
    ax.xaxis.set_major_formatter(ticker.EngFormatter())
    ax.yaxis.set_major_formatter(ticker.EngFormatter())
    plt.show()
示例#18
0
 def gen_graph(self):
     self.log.append(2,'Generating {} graph'.format(self.name))
     dates = mdates.date2num(self.x)
     plt.figure(figsize=(20,5))
     plt.plot_date(dates,self.y,'r')
     plt.title(self.name)
     option = sys.argv[1:]
     option = option[0]
     if option == '-d':
         loc = mdates.HourLocator(interval=1)
         fmt = mdates.DateFormatter('%H:%M')
         label = 'Time [h:m]'
     elif option == '-m':
         loc = mdates.DayLocator(interval=1)
         fmt = mdates.DateFormatter('%m.%d')
         label = 'Day [m.d]'
     elif option == '-w':
         loc = mdates.DayLocator(interval=1)
         fmt = mdates.DateFormatter('%d')
         label = 'Day [m.d]'
     plt.gca().xaxis.set_major_formatter(fmt)
     plt.gca().xaxis.set_major_locator(loc)
     plt.ticklabel_format(axis='y',style='plain')
     plt.gca().yaxis.set_major_formatter(ticker.EngFormatter(unit=self.units))
     plt.grid()
     plt.xlabel(label)
     if self.units == '':
         plt.ylabel('[amount]')
         plt.gca().yaxis.set_major_locator(ticker.MaxNLocator(integer=True))
     else:
         plt.ylabel('['+self.units+']')
     plt.savefig(self.ID+'.jpg')
     plt.close()
示例#19
0
def line_plot_day_by_day(data):
    data_by_time = data.groupby(
        ["ObservationDate",
         "Country/Region"])["Confirmed", "Deaths", "Recovered",
                            "Active_cases"].sum().reset_index(drop=True)
    plt.figure(figsize=(14, 9))
    ax = sns.lineplot(x=data_by_time.index,
                      y='Confirmed',
                      label='Confirmed',
                      data=data_by_time)
    sns.lineplot(x=data_by_time.index,
                 y='Active_cases',
                 label='Active_Cases',
                 data=data_by_time)
    sns.lineplot(x=data_by_time.index,
                 y='Deaths',
                 label='Deaths',
                 data=data_by_time)
    sns.lineplot(x=data_by_time.index,
                 y='Recovered',
                 label='Recovered',
                 data=data_by_time)
    ax.yaxis.set_major_formatter(ticker.EngFormatter())
    plt.title('Plotted day-by-day')
    plt.legend()
示例#20
0
def most_attacked_countries():
    df2 = df.select(col('TGTCOUNTRY').alias('TargetCountry'), col('NUMWEAPONSDELIVERED').alias('NumWeapons')) \
            .dropna() \
            .groupBy(col('TargetCountry')) \
            .agg(sum('NumWeapons').alias('TotalWeaponsDropped')) \
            .filter(col('TotalWeaponsDropped') > 0).filter(col('TargetCountry') != 'UNKNOWN') \
            .orderBy(col('TotalWeaponsDropped').desc())

    pandf = df2.toPandas()

    fig, ax = plt.subplots(figsize=(10, 9))

    ax.bar(pandf['TargetCountry'],
           pandf['TotalWeaponsDropped'],
           color='royalblue')
    ax.legend()

    #avoid scientific notation on Y-axis
    #ax.ticklabel_format(style='plain', axis='y')
    ax.yaxis.set_major_formatter(mpt.EngFormatter())

    plt.xticks(rotation=10)
    plt.xlabel("Attacked Countries")
    plt.ylabel("Number of Bombs dropped")
    plt.title("Vietnam War Most Affected Countries")
    plt.savefig(output_dir + "most_attacked_countries.png")
    plt.close(fig)
示例#21
0
def most_common_takeoff():
    df2 = df.select(col('TAKEOFFLOCATION').alias('Takeoff')) \
            .dropna() \
            .groupBy(col('Takeoff')) \
            .agg(count(lit(1)).alias('NumMissions')) \
            .filter(col('NumMissions') > 26000).filter(~(col('Takeoff').rlike('^WESTPAC.*$'))) \
            .orderBy(col('NumMissions').desc())

    pandf = df2.toPandas()

    fig, ax = plt.subplots(figsize=(16, 9))

    ax.bar(pandf['Takeoff'], pandf['NumMissions'], color='royalblue')
    ax.legend()

    #avoid scientific notation on Y-axis
    #ax.ticklabel_format(style='plain', axis='y')
    ax.yaxis.set_major_formatter(mpt.EngFormatter())

    plt.xticks(rotation=20)
    plt.xlabel("Take-off location")
    plt.ylabel("Number of Missions")
    plt.title("Vietnam War Most Common Take-off Locations")
    plt.savefig(output_dir + "most_common_takeoff.png")
    plt.close(fig)
示例#22
0
def make_thd_plot(thdplot, sinplot, voltages):
    thdplot.set_ylabel("thd (dB)")
    thdplot.set_xlabel("control current (mA)")
    thdplot.set_title("total harmonic distortion")
    sinplot.set_xticks([], [])
    #sinplot.set_yticks([],[])
    #sinplot.set_title("sine shape at cc = 1mA")
    #for voltage in np.arange(3,18, 1):
    for voltage in voltages:
        printall(ns.cmd("alter v1 %f" % voltage))
        printall(ns.cmd("alter v2 %f" % voltage))

        y = []
        x = my_logspace(0.01, 1, 8)
        for current in x:
            printall(ns.cmd("alter i1 %fm" % current))
            y.append(calc_thd(300))

        printall(ns.cmd("alter i1 40u"))
        _, signal, time = simulate_waveform(300,
                                            n_periods=1,
                                            steps_per_period=64)

        thdplot.plot(x / 1000, np.log10(y) * 10, label="+/- %fV" % voltage)
        sinplot.plot(time, signal)

    thdplot.set_xscale('log')

    fmt_mA = ticker.EngFormatter(unit='A')
    fmt_dB = ticker.FormatStrFormatter('%.0f dB')
    thdplot.xaxis.set_major_formatter(fmt_mA)
    thdplot.yaxis.set_major_formatter(fmt_dB)
示例#23
0
 def test_formatting(self, unit, input, expected):
     """
     Test the formatting of EngFormatter with some inputs, against
     instances with and without units. Cases focus on when no SI
     prefix is present, for values in [1, 1000).
     """
     fmt = mticker.EngFormatter(unit)
     assert fmt(input) == expected
示例#24
0
文件: viz.py 项目: pqwy/unmark
def barcompare(benches, *args, **kw):
    """barcompare (benchmarks, counters?, **keywords)

    Compares benchmark results as a bar-chart.

    Arguments:
    - benches  : Sequence of Benches.
    - counters : Counters to display.

    Keyword arguments:
    - title : Figure title.
    - est   : Regression estimator.
    - props : cycler.Cycler or other iterable yielding prop dicts for each counter.
    """

    benches = list(benches)
    counters = _as_seq(_pos(args, 0, 'time'))
    estf = kw.get('est', est.default)
    props = _counter_props(counters, kw.get('props'))

    w = int(ceil(sqrt(len(counters))))
    h = int(ceil(len(counters) / w))
    fs = plt.rcParams['figure.figsize']

    fig, axes = plt.subplots(nrows=h,
                             ncols=w,
                             squeeze=False,
                             sharey='row',
                             figsize=(w * fs[0],
                                      max(1,
                                          len(benches) * 0.1) * h * fs[1]))

    axes = [ax for row in axes for ax in row]
    for ax in axes[len(counters):]:
        ax.remove()

    names = [b.name for b in benches]
    ypos = arange(len(benches) - 1, -1, -1)

    for ctr, ax in zip(counters, axes):

        es = [bench.estimate(ctr, estf) for bench in benches]
        xerr = ([e.b - e.b_min for e in es], [e.b_max - e.b for e in es])

        ax.barh(ypos, [e.b for e in es],
                xerr=xerr,
                alpha=0.3,
                edgecolor=props[ctr]['color'],
                **props[ctr])

        ax.set_yticks(ypos)
        ax.set_yticklabels(names)

        unit = benches[0].unit(ctr) or ""
        ax.xaxis.set_major_formatter(ticker.EngFormatter(unit=unit))
        ax.set_xlabel(ctr)

    _fig_set_title(fig, kw.get('title'), estf)
def labelsGeneric(graph, paramsList):
    graph.yaxis.set_major_formatter(
        ticker.EngFormatter()
    )  #English formatter allows for the graph ticks to be displayed as 10K instead of 10000
    graph.set_title(paramsList[0])  #Set the graph title
    plt.xlabel(paramsList[3])  #Label the x axis
    plt.ylabel(paramsList[4])  #Label the y axis
    plt.ylim(int(paramsList[5]), int(
        paramsList[6]))  #Set the lower limit and upper limit of the yaxis
示例#26
0
def test_EngFormatter_formatting():
    """
    Create two instances of EngFormatter with default parameters, with and
    without a unit string ('s' for seconds). Test the formatting in some cases,
    especially the case when no SI prefix is present, for values in [1, 1000).

    Should not raise exceptions.
    """
    unitless = mticker.EngFormatter()
    assert unitless(0.1) == u'100 m'
    assert unitless(1) == u'1'
    assert unitless(999.9) == u'999.9'
    assert unitless(1001) == u'1.001 k'

    with_unit = mticker.EngFormatter(unit=u's')
    assert with_unit(0.1) == u'100 ms'
    assert with_unit(1) == u'1 s'
    assert with_unit(999.9) == u'999.9 s'
    assert with_unit(1001) == u'1.001 ks'
示例#27
0
def bar_plot_province(data):
    get_actual_values(data)
    data = data.groupby(["Province/State"
                         ])["Confirmed", "Active_cases", "Recovered",
                            "Deaths"].sum().reset_index().sort_values(
                                "Confirmed",
                                ascending=False).reset_index(drop=True)
    for each in columns:
        plt.figure(figsize=(14, 9))
        ax = sns.barplot(x=each, y='Province/State', data=data)
        ax.xaxis.set_major_formatter(ticker.EngFormatter())
        plt.title(str(each) + ' cases by time in each Province')
示例#28
0
def plot_gas_usage(es: Elasticsearch):
    body = {
        'aggs': {
            'half_hour': {
                'aggs': {
                    'used_gas': {
                        'avg': {
                            'field': 'gasUsed.num'
                        }
                    }
                },
                'date_histogram': {
                    'field': 'timestamp',
                    'interval': '30m',
                    'min_doc_count': 0
                }
            }
        },
        'query': {
            'bool': {
                'filter': [{
                    'range': {
                        'timestamp': {
                            'gte': 'now/d-7d',
                            'lte': 'now/d-1d'
                        }
                    }
                }]
            }
        },
        'size': 0
    }

    response = es.search(index='ethereum', body=body)
    data = response['aggregations']['half_hour']['buckets']

    x = [datetime.fromtimestamp(bucket['key'] / 1000) for bucket in data]
    y = [bucket['used_gas']['value'] for bucket in data]

    fig, ax = plt.subplots(1, 1)
    fig.set_size_inches(15, 6)
    ax.yaxis.set_major_formatter(mtick.EngFormatter())
    ax.set_xlabel('Date')
    ax.set_ylabel('Gas Usage')
    ax.plot(x, y)
    fig.autofmt_xdate()

    os.makedirs('plots', exist_ok=True)
    fig.savefig('plots/gas_usage_{}.png'.format(datetime.now().isoformat()),
                bbox_inches='tight')

    plt.show()
def labelsMultiple(graph, paramsList):
    graph.yaxis.set_major_formatter(
        ticker.EngFormatter()
    )  #English formatter allows for the graph ticks to be displayed as 10K instead of 10000
    graph.set_title(paramsList[0])  #Set the graph title
    plt.xlabel(paramsList[1])  #Label the x axis
    plt.ylabel(paramsList[2])  #Label the y axis
    xLimL, xLimH = limitCheck(int(paramsList[3]), int(
        paramsList[4]))  #Check for limits that might be entered wrongly
    yLimL, yLimH = limitCheck(int(paramsList[5]), int(
        paramsList[6]))  #Check for limits that might be entered wrongly
    plt.xlim(xLimL, xLimH)  #Set the lower limit and upper limit of the xaxis
    plt.ylim(yLimL, yLimH)  #Set the lower limit and upper limit of the yaxis
示例#30
0
def plot_ax(
    ax,
    file_lists,
    legend_pattern=".*",
    xlabel=None,
    ylabel=None,
    title=None,
    xlim=None,
    xkey='env_step',
    ykey='rew',
    smooth_radius=0,
    shaded_std=True,
    legend_outside=False,
):
    def legend_fn(x):
        # return os.path.split(os.path.join(
        #     args.root_dir, x))[0].replace('/', '_') + " (10)"
        return re.search(legend_pattern, x).group(0)

    legneds = map(legend_fn, file_lists)
    # sort filelist according to legends
    file_lists = [f for _, f in sorted(zip(legneds, file_lists))]
    legneds = list(map(legend_fn, file_lists))

    for index, csv_file in enumerate(file_lists):
        csv_dict = csv2numpy(csv_file)
        x, y = csv_dict[xkey], csv_dict[ykey]
        y = smooth(y, radius=smooth_radius)
        color = COLORS[index % len(COLORS)]
        ax.plot(x, y, color=color)
        if shaded_std and ykey + ':shaded' in csv_dict:
            y_shaded = smooth(csv_dict[ykey + ':shaded'], radius=smooth_radius)
            ax.fill_between(x,
                            y - y_shaded,
                            y + y_shaded,
                            color=color,
                            alpha=.2)

    ax.legend(legneds,
              loc=2 if legend_outside else None,
              bbox_to_anchor=(1, 1) if legend_outside else None)
    ax.xaxis.set_major_formatter(mticker.EngFormatter())
    if xlim is not None:
        ax.set_xlim(xmin=0, xmax=xlim)
    # add title
    ax.set_title(title)
    # add labels
    if xlabel is not None:
        ax.set_xlabel(xlabel)
    if ylabel is not None:
        ax.set_ylabel(ylabel)