示例#1
0
def categorical_horizontal_bar_numbers(dataset,
                                       filename: str,
                                       fig_dim=(10, 5),
                                       title="",
                                       x_label="",
                                       y_label="",
                                       data_type="date",
                                       title_fontsize=35):
    fmt = EngFormatter(places=0)
    data_options = ["date", "decision", "label"]
    if data_type not in data_options:
        raise ValueError("Invalid date_type. Expected one of: %s" %
                         data_options)

    fig, ax = plt.subplots(figsize=fig_dim)
    width = 0.75  # the width of the bars
    ind = np.arange(len(dataset.values()))  # the x locations for the groups
    ax.barh(ind, dataset.values(), width, color="#004561")
    plt.rcParams["font.weight"] = "bold"
    ax.set_yticks(ind + width / 2)
    ax.set_yticklabels(dataset.keys(), minor=False)
    plt.grid(False)
    plt.title(title, fontsize=title_fontsize)
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    ax.xaxis.set_major_formatter(fmt)
    for i, v in enumerate(dataset.values()):
        if data_type == data_options[0]:
            ax.text(v + 5000000,
                    i,
                    s=fmt.format_eng(v),
                    color='#1e343f',
                    va='center')
        elif data_type == data_options[1]:
            ax.text(v + 2000000,
                    i,
                    s=fmt.format_eng(v),
                    color='#1e343f',
                    va='center',
                    fontweight='bold')
            plt.tight_layout()
        elif data_type == data_options[2]:
            ax.text(v + 15,
                    i,
                    s=fmt.format_eng(v),
                    color='#1e343f',
                    va='center',
                    fontweight='bold')
    png_file = filename + ".png"
    path_to_png = add_path_to_plot_images_str(png_file)
    plt.savefig(path_to_png)
    # plt.savefig(path_to_png, format='png', bbox_inches='tight')
    plt.tight_layout()
    plt.show()
示例#2
0
def plot(all_data, key_to_plot, directory=".", eng_fmt=False):
    list_of_n = sorted(all_data.keys())
    samples = len(next(iter(all_data.values())))
    data = [[all_data[n][i][key_to_plot] for i in range(samples)]
            for n in list_of_n]
    data_mean = list(map(mean, data))
    data_min = list(map(min, data))
    data_max = list(map(max, data))
    data_dev = list(map(pstdev, data))

    ax = plt.gca()
    ax2 = ax.twinx()

    ax.plot(list_of_n, data_mean, label="mean")
    ax.plot(list_of_n, data_min, label="min/max", color='#808080')
    ax.plot(list_of_n, data_max, color='#808080')
    ax2.plot(list_of_n, data_dev, label="stdev", color='#d62728')

    ax.fill_between(list_of_n, data_min, data_max, color='#539caf', alpha=0.4)

    # x axis
    ax.set_xlabel('n')
    formatter = EngFormatter(sep="")
    ax.xaxis.set_major_formatter(formatter)
    # plt.xticks(np.arange(min(list_of_n), max(list_of_n)+1, 10000))

    # first y axis
    ax.set_ylabel(key_to_plot)
    if eng_fmt:
        ax.yaxis.set_major_formatter(formatter)
        ax.yaxis.set_major_locator(MaxNLocator(nbins='auto', integer=True))

    # second y axis
    ax1_range = max(data_max) - min(data_min)
    dev_middle = min(data_dev) + max(data_dev) / 2
    ax2.set_ylim([dev_middle - ax1_range / 2, dev_middle + ax1_range / 2])
    no_negative = lambda x, pos=None: "" if x < 0 else (formatter.format_eng(
        x) if eng_fmt else "%.2f" % x)
    ax2.yaxis.set_major_formatter(FuncFormatter(no_negative))

    ax.legend(loc=2)
    ax2.legend(loc=1)

    plt.savefig(os.path.join(directory, 'plot_{}.pdf'.format(key_to_plot)))
    plt.clf()
示例#3
0
    cmap_purples = mpl.cm.get_cmap('Purples')
    cmap_greens = mpl.cm.get_cmap('Greens')
    normalize = mpl.colors.Normalize(vmin=0, vmax=3)
    beta_colors = [cmap_blues(normalize(t)) for t in range(1, 4)]
    gamma_colors = [cmap_purples(normalize(t)) for t in range(1, 4)]
    qs_colors = [cmap_greens(normalize(t)) for t in range(1, 4)]

    # Plot beta3 only if available
    df_beta3 = fit_df[fit_df['inflection_point4'] != 0]
    #    df_beta3 = df_beta3.reset_index(drop=True)

    x12 = list(fit_df.index)
    x3 = list(df_beta3.index)

    x_labels_bottom = list(fit_df['Country/Region'])
    x_labels_top = [engfmt.format_eng(x) for x in list(fit_df['confirmed'])]

    mpl.rcParams.update(defaultPlotStyle)

    fig = plt.figure()
    fig.set_size_inches(6.5, 8.5, forward=True)
    fig.subplots_adjust(hspace=0.1, wspace=0.4)
    gs0 = gridspec.GridSpec(ncols=1, nrows=1, figure=fig, width_ratios=[1])
    gs00 = gridspec.GridSpecFromSubplotSpec(nrows=4,
                                            ncols=1,
                                            subplot_spec=gs0[0])

    ax1 = fig.add_subplot(gs00[0, 0])
    ax2 = fig.add_subplot(gs00[1, 0])
    ax3 = fig.add_subplot(gs00[2, 0])
    ax4 = fig.add_subplot(gs00[3, 0])
示例#4
0
# |-class matplotlib.ticker.PercentFormatter(xmax=100, decimals=None, symbol='%', is_latex=False)
xaxis = ax.get_xaxis()
pfx = PercentFormatter(
    xmax=10,  # 百分比的计算分母:输出值计算方式:x / xmax * 100. 比如千分比,使用10
    decimals=2,  # 小数点维数:精度
    symbol='‰$a^2$',  # 符号
    is_latex=True)  # 符号支持Latex语法
xaxis.set_major_formatter(pfx)
# 2.EngFormatter
# |-class matplotlib.ticker.EngFormatter(unit='', places=None, sep=' ')[source]
yaxis = ax.get_yaxis()
pfy = EngFormatter(
    unit='Hz',  # 单位(后缀)
    places=1,  # 小数位数
    sep='*')  # 前缀(常用符号见上面说明与文档说明)
print(pfy.format_eng(0.1))  # 100m
yaxis.set_major_formatter(pfy)

ax2 = figure.add_axes([0.1, 0.55, 0.8, 0.4])
# 3.FuncFormatter
# class matplotlib.ticker.FuncFormatter(func)
xaxis = ax2.get_xaxis()


def my_x_formatter_func(x, pos):
    if x and pos:
        print(type(x), x, type(pos), pos)
        return 'L:%5.2f(%d)' % (x, pos)
    else:
        return "o"
async def plot_csv(path,
                   total_confirmed,
                   total_recovered,
                   total_deaths,
                   logarithmic=False,
                   is_us=False,
                   is_daily=False):
    timeline, confirmed, recovered, deaths, active = await make_courbe(
        total_confirmed, total_recovered, total_deaths, is_us=is_us)
    alpha = .2
    fig, ax = plt.subplots()
    ax.spines['bottom'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)

    if logarithmic:
        plt.yscale('log')

    ax.xaxis.set_major_locator(MultipleLocator(7))
    ax.plot(timeline, deaths, "-", color="#e62712")
    ax.plot(timeline, confirmed, "-", color="orange")
    if not is_us:
        ax.plot(timeline, active, "-", color="yellow", alpha=0.5)
        ax.plot(timeline, recovered, "-", color="lightgreen")
        leg = plt.legend(["Deaths", "Confirmed", "Active", "Recovered"],
                         facecolor='0.1',
                         loc="upper left")
    else:
        leg = plt.legend(["Deaths", "Confirmed"],
                         facecolor='0.1',
                         loc="upper left")

    for text in leg.get_texts():
        text.set_color("white")
    ticks = [i for i in range(len(timeline)) if i % 60 == 0]
    plt.xticks(ticks, ha="center")
    ax.yaxis.grid(True)
    plt.ylabel("Data")
    plt.xlabel("Timeline (mm/dd/yy)")

    ax.xaxis.label.set_color('white')
    ax.yaxis.label.set_color('white')
    ax.tick_params(axis='x', colors='white')
    ax.tick_params(axis='y', colors='white')
    fig.autofmt_xdate()
    ax.fmt_xdata = mdates.DateFormatter("%M/%d/%y")

    if not logarithmic:
        ax.set_ylim(ymin=1)
    locs, _ = plt.yticks()

    if logarithmic:
        locs = list(map(lambda x: x * 100, locs[:-1]))
    formatter = EngFormatter(locs)

    plt.yticks(locs,
               [formatter.format_eng(int(iter_loc)) for iter_loc in locs])
    plt.savefig(path, transparent=True)

    plt.close('all')
async def plot_bar_daily(path, confirmed, recovered, deaths):
    timeline, confirmed, recovered, deaths = make_daily_courbe(
        confirmed, recovered, deaths)
    ticks = [i for i in range(len(timeline)) if i % 60 == 0]
    legs = []

    ax1 = plt.subplot(3, 1, 1)
    ax1.xaxis.label.set_color('white')
    ax1.yaxis.label.set_color('white')

    ax1.tick_params(axis='x', colors='white')
    ax1.tick_params(axis='y', colors='white')
    ax1.spines['bottom'].set_visible(False)
    ax1.spines['top'].set_visible(False)
    ax1.spines['right'].set_visible(False)
    ax1.spines['left'].set_visible(False)
    ax1.axes.get_xaxis().set_visible(False)
    plt.xticks(ticks, ha="center")
    labels = ["Confirmed"]
    handles = [plt.Rectangle((0, 0), 1, 1, color="orange") for label in labels]
    legs.append(
        plt.legend(handles,
                   labels,
                   facecolor='0.1',
                   loc="upper left",
                   prop={"size": 8}))
    ax1.bar(timeline, confirmed, color="orange")
    locs, _ = plt.yticks()
    formatter = EngFormatter(locs)
    plt.yticks(locs,
               [formatter.format_eng(int(iter_loc)) for iter_loc in locs])

    ax2 = plt.subplot(3, 1, 2)
    ax2.xaxis.label.set_color('white')
    ax2.yaxis.label.set_color('white')
    ax2.tick_params(axis='x', colors='white')
    ax2.tick_params(axis='y', colors='white')
    plt.xticks(ticks, ha="center")
    labels = ["Recovered"]
    handles = [
        plt.Rectangle((0, 0), 1, 1, color="lightgreen") for label in labels
    ]
    legs.append(
        plt.legend(handles,
                   labels,
                   facecolor='0.1',
                   loc="upper left",
                   prop={"size": 8}))
    ax2.spines['bottom'].set_visible(False)
    ax2.spines['top'].set_visible(False)
    ax2.spines['right'].set_visible(False)
    ax2.spines['left'].set_visible(False)
    ax2.axes.get_xaxis().set_visible(False)
    ax2.bar(timeline, recovered, color="lightgreen")
    locs, _ = plt.yticks()
    formatter = EngFormatter(locs)
    plt.yticks(locs,
               [formatter.format_eng(int(iter_loc)) for iter_loc in locs])

    ax3 = plt.subplot(3, 1, 3)
    ax3.xaxis.label.set_color('white')
    ax3.yaxis.label.set_color('white')
    ax3.tick_params(axis='x', colors='white')
    ax3.tick_params(axis='y', colors='white')
    plt.xticks(ticks, ha="center")
    labels = ["Deaths"]
    handles = [
        plt.Rectangle((0, 0), 1, 1, color="#e62712") for label in labels
    ]
    legs.append(
        plt.legend(handles,
                   labels,
                   facecolor='0.1',
                   loc="upper left",
                   prop={"size": 8}))
    ax3.spines['bottom'].set_visible(False)
    ax3.spines['top'].set_visible(False)
    ax3.spines['right'].set_visible(False)
    ax3.spines['left'].set_visible(False)
    ax3.bar(timeline, deaths, color="#e62712")
    locs, _ = plt.yticks()
    formatter = EngFormatter(locs)
    plt.yticks(locs,
               [formatter.format_eng(int(iter_loc)) for iter_loc in locs])
    plt.xlabel("Timeline (mm/dd/yy)")

    for leg in legs:
        for text in leg.get_texts():
            text.set_color("white")
    plt.savefig(path, transparent=True)
    plt.close('all')