Пример #1
0
def main():
    x = np.arange(0.0, 30, 0.1)
    y1 = 0.1 * x * np.sin(x)
    y2 = 0.001 * x**3 - 0.03 * x**2 + 0.12 * x

    fig = plt.figure(figsize=(10, 4))
    ax11 = fig.add_subplot(121)
    ax12 = ax11.twinx()

    ax11.plot(x, y1, color='blue', label='plot 1')
    ax12.plot(x, y2, color='red', label='plot 2')
    ax11.hlines(y=0, xmin=0, xmax=30)

    ax11.set_title('Original')
    ax11.set_ylabel('Plot 1', color='blue')
    ax12.set_ylabel('Plot 2', color='red')
    ax11.set_xlim(0.0, 30.0)

    ax21 = fig.add_subplot(122)
    ax22 = ax21.twinx()

    ax21.plot(x, y1, color='blue', label='plot 1')
    ax22.plot(x, y2, color='red', label='plot 2')
    ax21.hlines(y=0, xmin=0, xmax=30)

    ax21.set_title('Using mpl_axes_aligner.align')
    ax21.set_ylabel('Plot 1', color='blue')
    ax22.set_ylabel('Plot 2', color='red')
    ax21.set_xlim(0.0, 30.0)

    align.yaxes(ax21, 0, ax22, 0, 0.5)
    plt.tight_layout()
    plt.savefig("intro_plt.png")
Пример #2
0
    def plot_option_pnl(self):
        """
        Plot holding period return

        Returns
        -------

        """
        fig, ax1 = plt.subplots(figsize=(12, 6))
        ax1.plot(self.trading_days, self.option_return, 'r-^', label='Option')
        ax1.axhline(0, color='k', linestyle=':')
        ax2 = ax1.twinx()
        ax2.plot(self.trading_days,
                 self.underlying_return,
                 'b-o',
                 label='Underlying')
        ax1.legend(loc="upper left")
        ax2.legend(loc="upper right")
        ax1.spines['top'].set_visible(False)
        ax2.spines['top'].set_visible(False)
        ax1.set_xlabel("Date")
        ax1.set_ylabel("Option P&L")
        ax2.set_ylabel("Underlying P&L")
        ax1.yaxis.set_major_formatter(mtick.PercentFormatter())
        ax2.yaxis.set_major_formatter(mtick.PercentFormatter())

        # Align y-axes
        org1 = 0.0  # Origin of first axis
        org2 = 0.0  # Origin of second axis
        pos = 0.5  # Position the two origins are aligned
        align.yaxes(ax1, org1, ax2, org2, pos)
        plt.tight_layout()
        plt.title('Holding Period Return')
Пример #3
0
def main3():
    x = np.arange(0.0, 30, 0.1)
    y1 = 0.1 * x * np.sin(x)
    y2 = 0.001 * x**3 - 0.03 * x**2 + 0.12 * x

    fig = plt.figure(figsize=(6.8, 2.55), dpi=100)
    ax11 = fig.add_subplot(121)
    ax12 = ax11.twinx()

    ax11.plot(x, y1, color='blue', label='plot 1')
    ax12.plot(x, y2, color='red', label='plot 2')
    ax11.hlines(y=0, xmin=0, xmax=30, linewidth=1)

    ax11.set_title('align.yaxes(ax1, 0, ax2, 0, 0.2)')
    ax11.set_ylabel('Plot 1', color='blue')
    ax12.set_ylabel('Plot 2', color='red')
    ax11.set_xlim(0.0, 30.0)

    ax21 = fig.add_subplot(122)
    ax22 = ax21.twinx()

    ax21.plot(x, y1, color='blue', label='plot 1')
    ax22.plot(x, y2, color='red', label='plot 2')
    ax21.hlines(y=0, xmin=0, xmax=30, linewidth=1)

    ax21.set_title('align.yaxes(ax1, 0, ax2, 0, 0.8)')
    ax21.set_ylabel('Plot 1', color='blue')
    ax22.set_ylabel('Plot 2', color='red')
    ax21.set_xlim(0.0, 30.0)

    align.yaxes(ax11, 0, ax12, 0, 0.2)
    align.yaxes(ax21, 0, ax22, 0, 0.8)
    plt.tight_layout()
    plt.savefig("align_plt3.png")
Пример #4
0
def test_yaxes_pos_ValueError(pos):
    fig.clear()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()
    org1 = 0.0
    org2 = 0.0
    with pytest.raises(ValueError):
        align.yaxes(ax1, org1, ax2, org2, pos)
Пример #5
0
def test_yaxes_outrange_ValueError():
    fig.clear()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()
    ax1.set_ylim(-1.0, 0.0)
    ax2.set_ylim(0.0, 1.0)
    org1 = 0.5
    org2 = 1.1
    with pytest.raises(ValueError):
        align.yaxes(ax1, org1, ax2, org2)
Пример #6
0
def test_yaxes_simple2():
    fig.clear()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()
    ax1.set_ylim(-1.0, 0.0)
    ax2.set_ylim(0.0, 1.0)
    org1 = 0.0
    org2 = 0.0
    align.yaxes(ax1, org1, ax2, org2)
    assert ax1.get_ylim() == (-1.0, 1.0)
    assert ax2.get_ylim() == (-1.0, 1.0)
Пример #7
0
def add_fieldmaps_to_axes(lattice, axes, bounds=None, sections='All',
                           fields=['cavity', 'solenoid'],
                           magnets = ['quadrupole', 'dipole', 'beam_position_monitor', 'screen'],
                          include_labels=True, verbose=False):
    """
    Adds fieldmaps to an axes.

    """

    max_scale = 0

    fmaps = load_elements(lattice, bounds=bounds, sections=sections, verbose=verbose, types=fields)
    ax1 = axes

    ax1rhs = ax1.twinx()
    ax = [ax1, ax1rhs]

    ylabel = {'cavity': '$E_z$ (MV/m)', 'solenoid':'$B_z$ (T)'}
    color = {'cavity': 'green', 'solenoid':'blue'}

    for i, section in enumerate(fields):
        a = ax[i]
        for name, data in fmaps[section].items():
            label = f'{section}_{name}'
            c = color[section]
            # if section == 'cavity':# and not section == 'solenoid':
            if section == fields[0]:
                max_scale = max(abs(data[:,1])) if max(abs(data[:,1])) > max_scale else max_scale
            a.plot(*data.T, label=label, color=c)
        a.set_ylabel(ylabel[section])
    ax1.set_xlabel('$z$ (m)')

    if len(fields) < 1:
        for a in ax:
            a.set_yticks([])

    max_scale = 1 if max_scale == 0 else max_scale
    a = ax[0]

    fmaps = load_elements(lattice, bounds=bounds, sections=sections, verbose=verbose, types=magnets, scale=max_scale)
    for section in magnets:
        if len(fmaps[section].items()) > 0:
            section_scale = max_scale #/ max([max(abs(d[:,1])) for d in fmaps[section].values()])
        for name, (data, c) in fmaps[section].items():
            # c = color[section]
            data[:,1] = data[:,1] * section_scale
            a.fill(*data.T, color=c)

    data = np.array([[0,0], [100,0]])
    ax[0].plot(*data.T, color='black')
    if bounds:
        ax1.set_xlim(bounds[0], bounds[1])

    align.yaxes(ax[0], 0, ax[1], 0, 0.5)
Пример #8
0
def test_yaxes_axes_TypeError():
    fig.clear()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()
    ax3 = ax1.get_yaxis()
    org1 = 0.0
    org2 = 0.0
    pos = 0.5
    with pytest.raises(TypeError):
        align.yaxes(ax3, org1, ax2, org2, pos)
    with pytest.raises(TypeError):
        align.yaxes(ax1, org1, ax3, org2, pos)
Пример #9
0
def plot_study(curr_date, prev_date, uk_active_cases, prev_uk_active_cases):

    prev_data_end = prev_date + timedelta(days=1)
    diff = uk_active_cases[cases].sub(prev_uk_active_cases[cases],
                                      fill_value=0)
    diff[prev_data_end:] = nan

    curr_est = uk_active_cases[cases].iloc[-1]

    month_ago = curr_date - timedelta(days=30)
    start = min(month_ago, diff.index.min() - timedelta(days=7))

    data_colour = '#113377'
    diff_colour = '#015c00'
    curr_colour = 'red'
    fig, ax = plt.subplots(figsize=(14, 4))
    fig.set_facecolor('white')

    data_to_plot = uk_active_cases[cases][start:]
    data_to_plot.plot(ax=ax, grid=True, color=data_colour)
    ax.set_title(f'ZOE COVID Symptom Study as of {curr_date:%d %b %Y}')
    ax.xaxis.grid(True, which='minor')
    ax.tick_params(axis='y', labelcolor=data_colour)
    ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
    ax.set_ylabel('Predicted # of active cases', color=data_colour)

    ax.axhline(y=curr_est, color=curr_colour, zorder=-100)
    trans = transforms.blended_transform_factory(
        ax.get_yticklabels()[0].get_transform(), ax.transData)
    ax.text(1,
            curr_est + 1000,
            "{:,.0f}".format(curr_est),
            color=curr_colour,
            transform=trans,
            ha="right",
            va="bottom",
            zorder=1000)
    ax.patch.set_visible(False)

    diff_ax = ax.twinx()
    diff_ax.set_zorder(-1)
    diff_ax.tick_params(axis='y', labelcolor=diff_colour)
    diff_ax.set_ylabel(f'Change since {prev_date:%d %b %Y}', color=diff_colour)
    diff_to_plot = diff.loc[start:].reindex(data_to_plot.index)
    _ = diff_to_plot.plot(ax=diff_ax,
                          drawstyle='steps',
                          color=diff_colour,
                          zorder=-1)

    align.yaxes(ax, curr_est, diff_ax, 0, 0.3)
Пример #10
0
def test_yaxes_inverted():
    fig.clear()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()
    ax1.set_ylim(1.0, -1.0)
    ax2.set_ylim(1.5, 0.0)
    org1 = 0.0
    org2 = 0.0
    pos = 0.5
    align.yaxes(ax1, org1, ax2, org2, pos)
    lim1 = list(ax1.get_ylim())
    lim2 = list(ax2.get_ylim())
    assert lim1[0] > lim1[1]
    assert lim2[0] > lim2[1]
Пример #11
0
def demo(pet, pwe, tth, spe_pre, leng, wave, cid, mode, full=False):
    penum = len(tth)
    print('PEnum is {}'.format(penum))
    pf0 = np.zeros(leng)
    pf1 = np.zeros(leng)
    if mode == 'Weight':
        tru_pet = tth['RiseTime']
        t, c = np.unique(tru_pet, return_counts=True)
        pf0[t] = c
        pf1[pet] = pwe
        xlabel = '$PEnum/\mathrm{1}$'
        distd = '(W/ns,P/1)'
        distl = 'pdist'
        Q = penum
        q = np.sum(pwe)
        edist = np.abs(Q - q) * scipy.stats.poisson.pmf(Q, Q)
    elif mode == 'Charge':
        t = tth['RiseTime']
        w = tth[mode]
        t = np.unique(t)
        c = np.array([np.sum(w[tth['RiseTime'] == i]) for i in t])
        pf0[t] = c / spe_pre['spe'].sum()
        pf1[pet] = pwe / spe_pre['spe'].sum()
        xlabel = '$Charge/\mathrm{mV}\cdot\mathrm{ns}$'
        distd = '(W/ns,C/mV*ns)'
        distl = 'cdiff'
        edist = pwe.sum() - c.sum()
    print('truth RiseTime = {}, Weight = {}'.format(t, c))
    wave0 = np.convolve(spe_pre['spe'], pf0, 'full')[:leng]
    print('truth Resi-norm = {}'.format(np.linalg.norm(wave - wave0)))
    print('RiseTime = {}, Weight = {}'.format(pet, pwe))
    wdist = scipy.stats.wasserstein_distance(t,
                                             pet,
                                             u_weights=c,
                                             v_weights=pwe)
    print('wdist = {},'.format(wdist) + distl + ' = {}'.format(edist))
    wave1 = np.convolve(spe_pre['spe'], pf1, 'full')[:leng]
    print('Resi-norm = {}'.format(np.linalg.norm(wave - wave1)))

    fig = plt.figure()
    fig.tight_layout()
    ax = fig.add_subplot(111)
    ax.grid()
    ax2 = ax.twinx()
    ax.plot(wave, c='b', label='origin wave')
    ax.plot(wave0, c='k', label='truth wave')
    ax.plot(wave1, c='C1', label='recon wave')
    ax.set_xlabel('$Time/\mathrm{ns}$')
    ax.set_ylabel('$Voltage/\mathrm{mV}$')
    ax.hlines(spe_pre['thres'], 0, 1029, color='c', label='threshold')
    ax2.set_ylabel(xlabel)
    fig.suptitle(
        'eid={},cid={},'.format(tth['EventID'][0], tth['ChannelID'][0]) +
        distd + '-dist={:.2f},{:.2f}'.format(wdist, edist))
    ax2.vlines(t, 0, c, color='g', label='truth ' + mode)
    ax2.vlines(pet, -pwe, 0, color='y', label='recon ' + mode)
    lines, labels = ax.get_legend_handles_labels()
    lines2, labels2 = ax2.get_legend_handles_labels()
    align.yaxes(ax, 0, ax2, 0)
    ax2.legend(lines + lines2, labels + labels2)
    if full:
        ax.set_xlim(max(t.min() - 50, 0), min(t.max() + 150, leng))
    fig.savefig('img/demoe{}c{}.png'.format(tth['EventID'][0],
                                            tth['ChannelID'][0]),
                bbox_inches='tight')
    fig.clf()
    plt.close(fig)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(spe_pre['spe'], c='b')
    ax.grid()
    ax.set_xlabel('$Time/\mathrm{ns}$')
    ax.set_ylabel('$Voltage/\mathrm{mV}$')
    fig.savefig('img/spe{}.png'.format(cid), bbox_inches='tight')
    fig.clf()
    return
Пример #12
0
# set format of y-axis ticks
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))

# twin object for two different y-axis on the sample plot
ax2 = ax.twinx()
# make a plot with different y-axis using second axis object
ax2.plot(case_per_100k.Date,
         case_per_100k["Case_per_100K_7MA"],
         color="blue",
         marker="",
         label="Daily cases per 100,000, 7 day moving average")
ax2.set_ylabel("Cases per 100,000 Population\n7 Day Moving Average",
               color="black",
               fontsize=28)
# align secondary y-axis with primary y-axis
align.yaxes(ax, 0, ax2, 0)
# set fontsize of ticks
ax2.tick_params(axis='y', labelsize=24)

# remove top line
ax.spines['top'].set_visible(False)

# add legend
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2,
           labels + labels2,
           loc="upper left",
           prop=dict(size=18))

# add data labels
Пример #13
0
        ylabel='% ospedalizzati',
        xlabel='Data')
ax1.legend(loc=3)
ax2 = ax1.twinx()  # secondo axes che condivide lo stesso asse
ax2.bar(df_a.index,
        df_a['terapia_intensiva'].values,
        label='terapia intensiva',
        color=c2,
        alpha=0.25)
ax2.set_ylim(0, 5000)
ax2.legend(loc=4)
# Adjust the plotting range of two y axes
org1 = 0.0  # Origin of first axis
org2 = 0.0  # Origin of second axis
pos = 0.1  # Position the two origins are aligned
align.yaxes(ax1, org1, ax2, org2, pos)
plt.savefig(folder + 'plot_incrementi_pct2.jpg')
plotlist.append('plot_incrementi_pct2.jpg')

# grafico crescita parametri
x = df_a.index.values
y1 = df_a[[
    'ricoverati_con_sintomi', 'terapia_intensiva', 'isolamento_domiciliare'
]].values
y2 = df_a[[
    'ricoverati_con_sintomi_incr', 'terapia_intensiva_incr',
    'isolamento_domiciliare_incr'
]].values
lab = ['ricoverati con sintomi', 'terapia intensiva', 'isolamento domiciliare']
fig, ax = plt.subplots(2, 1, figsize=(14, 12))
ax1 = plt.subplot(211)