Exemplo n.º 1
0
def plot_figure(style='default'):
    """Setup and plot the demonstration figure with a given style.
    """
    plt.style.use("default")  # reset
    plt.style.use(style)

    # Use a dedicated RandomState instance to draw the same "random" values
    # across the different figures.
    prng = np.random.RandomState(96917002)

    # Tweak the figure size to be better suited for a row of numerous plots:
    # double the width and halve the height. NB: use relative changes because
    # some styles may have a figure size different from the default one.

    figures, axs = zip(*[plt.subplots() for _ in range(6)])

    plot_scatter(axs[0], prng)
    plot_image_and_patch(axs[1], prng)
    plot_bar_graphs(axs[2], prng)
    plot_colored_circles(axs[3], prng)
    plot_colored_sinusoidal_lines(axs[4])
    plot_histograms(axs[5], prng)

    if style == 'cyberpunk':
        for ax in axs:
            mplcyberpunk.make_lines_glow(ax)

    for fig in figures:
        fig.tight_layout()

    return figures
Exemplo n.º 2
0
def test_plotting_working_individual_functions():
    plt.style.use("cyberpunk")

    values = {c: [random.randint(0, 10) for _ in range(7)] for c in 'ABCDEF'}
    df = pd.DataFrame(values)

    df.plot(marker='o')
    mplcyberpunk.make_lines_glow()
    mplcyberpunk.add_underglow()

    plt.savefig("test_individual.png")
Exemplo n.º 3
0
def freq_analysis(input_text: str) -> None:
    character_freq = [input_text.count(i) for i in alphabet]
    table = dict(
        zip(alphabet,
            character_freq))  # словарь{буква_алфавита: частота_в_шифротексте}
    print(table)

    table1 = list(table.items())

    table1.sort(key=lambda i: i[1],
                reverse=True)  # словарь в список с сортировкой по value
    table1 = [x[0] for x in table1]

    # словарь {буква_в_частотном алфавите : буква_алфавита_с_макс_частотой }
    new_table = dict(zip(
        table1, freq_alphabet))  # словарь {шифр_символ: настоящий_символ}
    print(new_table)

    table2 = list(table.items())
    table2.sort(key=lambda i: i[1], reverse=True)
    table2 = [x[1] for x in table2]

    plt.bar(table.keys(), table.values(), width=0.7)
    plt.show()
    plt.bar(new_table.keys(), table2, width=0.7)
    mplcyberpunk.make_lines_glow()
    mplcyberpunk.add_underglow()
    plt.show()

    # output_text = [(i, char) for i in len(text) for char in text ]
    '''
    Теперь надо заменить буквы в input.txt по словарю new_table:
    если буква = ключу словаря, то заменяем ее на значение словаря
    '''

    new_table = list(new_table.items())
    print(new_table)
    new_text = ''

    for i in text:
        for j in new_table:
            if i in j and i == j[0]:
                i = j[1]
                new_text += i
                break

    with open('output.txt', mode='w') as file:
        file.write(new_text)
Exemplo n.º 4
0
def test_linestyle_attributes_copied():

    plt.style.use("cyberpunk")

    values = {c: [random.randint(0, 10) for _ in range(7)] for c in 'A'}
    df = pd.DataFrame(values)

    marker = 'x'
    linestyle = '--'
    df.plot(marker=marker, linestyle=linestyle)

    n_glow_lines = 10
    mplcyberpunk.make_lines_glow(n_glow_lines=n_glow_lines)

    # check number of lines
    lines = plt.gca().lines
    assert len(lines) == 1 + n_glow_lines

    # check line styling attributes
    for line in lines:
        assert line.get_marker() == marker
        assert line.get_linestyle() == linestyle
Exemplo n.º 5
0
def plot_figure(style_label="", n_columns=6):
    """Setup and plot the demonstration figure with a given style.
    """
    # Use a dedicated RandomState instance to draw the same "random" values
    # across the different figures.
    prng = np.random.RandomState(96917002)

    # Tweak the figure size to be better suited for a row of numerous plots:
    # double the width and halve the height. NB: use relative changes because
    # some styles may have a figure size different from the default one.
    n_rows = math.ceil(6/n_columns)

    (fig_width, fig_height) = plt.rcParams['figure.figsize']
    fig_size = [fig_width * n_columns, fig_height * n_rows]

    fig, axs = plt.subplots(ncols=n_columns,
                            nrows=n_rows,
                            num=style_label,
                            figsize=fig_size,
                            squeeze=False)
    axs = [item for sublist in axs for item in sublist]
    #axs[0].set_ylabel(style_label)

    plot_scatter(axs[0], prng)
    plot_image_and_patch(axs[1], prng)
    plot_bar_graphs(axs[2], prng)
    plot_colored_circles(axs[3], prng)
    plot_colored_sinusoidal_lines(axs[4])
    plot_histograms(axs[5], prng)

    if style_label == 'cyberpunk':
        for ax in axs:
            mplcyberpunk.make_lines_glow(ax)

    fig.tight_layout()

    return fig
Exemplo n.º 6
0
    seconds.append(a_timedelta.total_seconds())

# Compound Concentrations
compound_conc = [
    '200 uM', '100 uM', '50 uM', '25 uM', '12.5 uM', '6.25 uM', '3.125 uM',
    '1.5625 uM', '0.78125 uM', '0.3906 uM', '0.1953 uM', '+Control (Protein)'
]

# Colors for Each Line
line_colors = [
    '#03045e', '#023e8a', '#0077b6', '#0096c7', '#00b4d8', '#48cae4',
    '#90e0ef', '#ade8f4', '#caf0f8', '#D6EAF8', '#EBF5FB', 'yellow'
]

# Plot DataFrame
plt.style.use("cyberpunk")
for i in df_mean.columns:
    # plt.plot(seconds, df_4[i], marker='o', label=compound_conc[i-1], color=line_colors[i-1])
    plt.plot(seconds,
             df_mean[i],
             marker='o',
             label=compound_conc[i - 1],
             color=line_colors[i - 1])
plt.plot(seconds, df_5[1], marker='o', label='-Control (No Prot)', color='red')

plt.legend()
plt.title('Compound in 5% DMSO')
plt.xlabel('Time (s)', fontsize=12)
plt.ylabel('Absorbance (405 nm)', fontsize=12)
mplcyberpunk.make_lines_glow()
plt.show()
Exemplo n.º 7
0
    def PlotResults(self, Normalized=False):
        # Plot the data on three separate curves for S(t), I(t) and R(t)
        if Normalized == True:
            N = self.N
        else:
            N = 1.0

        fig = plt.figure(figsize=(7, 9))

        try:
            fig.suptitle('Model vs. Data - ' + self.Data.country + ' - ' +
                         self.Data.state)
        except:
            fig.suptitle('Model vs. Data - ' + self.Data.country)

        ax = fig.add_subplot(211, axisbelow=True)
        #ax.plot(self.t, self.S/N, 'blue', alpha=0.5, lw=2, label='Susceptible')
        #ax.plot(self.t, self.E/N, 'yellow', alpha=0.5, lw=2, label='Exposed')
        #ax.plot(self.t, self.I/N, 'red', alpha=0.5, lw=2, label='Infected')
        #ax.plot(self.t, self.Q/N, 'orange', alpha=0.5, lw=2, label='Quarantined')
        #ax.plot(self.t, self.P/N, 'teal', alpha=0.5, lw=2, label='Insusceptible')
        #ax.plot(self.t, self.Total/N, 'brown', alpha=0.5, lw=2, label='Total')

        ax.plot(self.t, self.C / N, label='Confirmed (Model)')
        ax.plot(self.t, self.D / N, label='Dead (Model)')

        try:
            ax.scatter(self.Data.Days,
                       self.Data.C / N,
                       s=5,
                       label='Confirmed (Data)')
            ax.scatter(self.Data.Days,
                       self.Data.D / N,
                       s=5,
                       label='Death (Data)')

            if self.Data.country != 'Canada':
                ax.plot(self.t, self.R / N, label='Recovered (Model)')
                ax.scatter(self.Data.Days,
                           self.Data.R / N,
                           s=5,
                           label='Recovered (Data)')
        except:
            pass

        #ax.set_xlabel('Time (days)')
        ax.set_ylabel('Number (log)')
        #ax.set_ylim(0,1.2)
        ax.yaxis.set_tick_params(length=0)
        ax.xaxis.set_tick_params(length=0)
        #ax.grid(b=True, which='major', c='w', lw=2, ls='-')
        #		legend = ax.legend()
        #		legend.get_frame().set_alpha(0.5)
        for spine in ('top', 'right', 'bottom', 'left'):
            ax.spines[spine].set_visible(False)

        ax.set_yscale('log')
        ############################
        ax2 = fig.add_subplot(212, axisbelow=True)
        ax2.plot(self.t, self.C / N, label='Confirmed (Model)')
        ax2.plot(self.t, self.D / N, label='Dead (Model)')

        try:
            ax2.scatter(self.Data.Days,
                        self.Data.C / N,
                        s=5,
                        label='Confirmed (Data)')
            ax2.scatter(self.Data.Days,
                        self.Data.D / N,
                        s=5,
                        label='Death (Data)')

            if self.Data.country != 'Canada':
                ax2.plot(self.t, self.R / N, label='Recovered (Model)')
                ax2.scatter(self.Data.Days,
                            self.Data.R / N,
                            s=5,
                            label='Recovered (Data)')

        except:
            pass

        ax2.set_xlabel('Time (days)')
        ax2.set_ylabel('Number')
        ax2.yaxis.set_tick_params(length=0)
        ax2.xaxis.set_tick_params(length=0)

        legend = ax2.legend()
        legend.get_frame().set_alpha(0.5)
        for spine in ('top', 'right', 'bottom', 'left'):
            ax2.spines[spine].set_visible(False)

        ##############
        mplcyberpunk.make_lines_glow(ax)
        mplcyberpunk.make_lines_glow(ax2)
        plt.show()
Exemplo n.º 8
0
def plot_tariff(tariff: pd.DataFrame,
                timeFrom_series: str,
                timeTo_series: str,
                value_series: str,
                saveTo: str = None) -> pd.DataFrame:
    plt.style.use("cyberpunk")

    tariff['diff'] = -tariff[value_series].diff(periods=1)

    fig, ax = plt.subplots()

    # Create step functions
    timeFrom = tariff[timeFrom_series].repeat(2).values[:-1]
    value = tariff[value_series].repeat(2).values[1:]

    x, pos = split_array(timeFrom, value, 0, True)
    _, neg = split_array(timeFrom, value, 0, False)

    ax.plot(x, pos, color='c')
    ax.plot(x, neg, color='r')

    # Set x axis labels
    freq = '3H'
    t = pd.date_range(tariff[timeFrom_series].min().ceil(freq),
                      tariff[timeFrom_series].max(),
                      freq=freq)
    ax.set_ylabel('Tariff (p/kWh)')
    ax.set_xticks(t)
    ax.set_xticklabels(
        [time.time().strftime("%I %p").lstrip('0') for time in t], rotation=90)

    def label(label_series: pd.Series, text_offset: Tuple[float, float]):
        # Wrapper for annotate method
        xlim = [mpl.dates.num2date(l) for l in ax.get_xlim()]
        xaxis_range = (xlim[1] - xlim[0]).total_seconds() / 60 / 60

        strftime = "%I %p" if label_series[timeTo_series].strftime(
            "%M") == "00" else "%I:%M %p"
        x_shift_hrs = text_offset[0] * xaxis_range

        ax.annotate(
            label_series[timeTo_series].strftime(strftime).lstrip('0'),
            xy=(label_series[timeTo_series],
                label_series[value_series] + label_series['diff'] / 2),
            xytext=(label_series[timeTo_series] +
                    pd.Timedelta(f'{x_shift_hrs} hours'),
                    (label_series[value_series] + label_series['diff'] / 2) *
                    text_offset[1]),
            arrowprops={'arrowstyle': '->'})

    # table start and end times of large jumps in price
    for big_step in tariff[tariff['diff'] > 10].iterrows():
        big_step = big_step[1]
        label(
            big_step,
            (-0.1 if big_step[timeTo_series].strftime("%M") == "00" else -0.12,
             1.1))

    for big_step in tariff[tariff['diff'] < -10].iterrows():
        big_step = big_step[1]
        label(big_step, (0.04, 1.1))

    mplcyberpunk.make_lines_glow()
    mplcyberpunk.add_underglow()

    if saveTo is not None:
        plt.savefig(saveTo, bbox_inches='tight')
    else:
        return ax