Ejemplo n.º 1
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")
Ejemplo n.º 2
0
def test_axis_limits_unchanged_by_underglow():
    plt.style.use("cyberpunk")

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

    df.plot(marker='o')

    ax = plt.gca()
    xlims, ylims = ax.get_xlim(), ax.get_ylim()

    mplcyberpunk.add_underglow(ax)

    assert xlims == ax.get_xlim()
    assert ylims == ax.get_ylim()
Ejemplo 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)
Ejemplo n.º 4
0
def plot(kernel: Kernel, params: dict = None, ax=None, xrange: Tuple[float, float] = (-10, 10.)):
    """
    Plot the kernel's shape.

    :param kernel: The kernel function
    :param params: A dictionary containing the kernel parameters
    :param ax: An optional matplotlib axes
    :param xrange The tuple pair lower and upper values over which the kernel should be evaluated.
    :return:
    """
    if params is None:
        params = initialise(kernel)

    cols = get_colours()
    if ax is None:
        fig, ax = plt.subplots()

    X = jnp.linspace(xrange[0], xrange[1], num=200).reshape(-1, 1)
    x1 = jnp.array([[0.0]])
    K = gpjax.kernels.cross_covariance(kernel, X, x1, params)
    ax.plot(X, K.T, color=cols['base'])
    mplcyberpunk.add_underglow(ax=ax)
Ejemplo n.º 5
0
# 数据
x = np.arange(-7, 7, 0.1)
y1 = np.sin(x)
y2 = np.sin(x) + x
y3 = np.sin(x) * x
y4 = np.sin(x) / x
plt.plot(x, y1)
plt.plot(x, y2)
plt.plot(x, y3)
plt.plot(x, y4)

# 线条发光
mplcyberpunk.make_lines_glow()
# 面积图
mplcyberpunk.add_underglow()

plt.show()

# time
t = np.arange(0, 6.4, 0.1)
# frequency
f = 1
amplitudes = np.arange(-10, 11, 1)
# amplitude
A = [x * np.cos(f * t) for x in amplitudes]

# 设置颜色样式,cool、spring、winter、tab20、coolwarm
colormap_sect = np.linspace(0, 1, len(amplitudes))
colors = [cm.cool(x) for x in colormap_sect]
Ejemplo n.º 6
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
Ejemplo n.º 7
0
 def plow():
     mplcyberpunk.add_glow_effects()
     mplcyberpunk.add_underglow()