def treemap_count(
    count_dict,
    question_title=None,
    cmap=matplotlib.cm.Oranges,
    figsize=(20, 9.0),
    output_filename=None,
    format_="pdf"
):
    plt.clf()
    my_values = list(count_dict.values())

    # create a color palette, mapped to these values
    mini = min(my_values)
    maxi = max(my_values)
    norm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)
    colors = [cmap(norm(value)) for value in my_values]

    # Change color
    fig, ax = plt.subplots(1, figsize=figsize)
    squarify.plot(
        sizes=my_values, label=list(count_dict.keys()), alpha=0.8, color=colors, ax=ax,text_kwargs={"fontsize":16}
    )
    plt.axis("off")
    if question_title:
        plt.title(
            "Occurences des mots du lexique dans les réponses à la question : \n{0}".format(
                question_title
            )
        )
    if output_filename:
        plt.savefig(output_filename, bbox_inches="tight", format=format_ ,transparent=True)
    else:
        plt.show()
Exemple #2
0
    def setup_labels_for_aggregated_nodemap(self, labels, figure_id, title,
                                            output_filename):

        plt.figure(figure_id)
        plt.title(title)

        display_sizes = []
        display_labels = []

        for node in self.aggregated_node_map:

            display_sizes.append(len(node.input_vector_weights))

            lbl_str = ''
            for idx, input_vector_weight in enumerate(
                    node.input_vector_weights):

                if idx % 3 != 0:
                    lbl_str += str(
                        labels[input_vector_weight.weight_label]) + ','
                else:
                    lbl_str += '\n' + str(
                        labels[input_vector_weight.weight_label]) + ','
            display_labels.append(lbl_str)

        squarify.plot(sizes=display_sizes, label=display_labels, alpha=.6)
        plt.axis('off')
        plt.savefig(output_filename + '.jpeg', dpi=1200)
Exemple #3
0
def create_treemap(t):
    string = tree.export_text(t, show_weights=True, spacing=1)
    feature_label_stack = list()
    labels = list()
    values = list()
    while string.find("feature") != -1:
        string, feature_label = extract_feature_label(string)
        feature_label_stack = clean_feature_label_stack(
            feature_label_stack, feature_label)
        if (string.find("weights") <
                string.find("feature")) or (string.find("feature") == -1):
            label, value = extract_feature_properties(string)
            labels.append(
                generate_label(feature_label_stack) + feature_label + label)
            values.append(value)
        else:
            feature_label_stack.insert(0, feature_label)
    sorted_labels = list()
    sizes = list()
    while len(labels) != 0:
        maximum = max(values)
        i = len(labels)
        while maximum in values:
            index = values.index(maximum)
            sorted_labels.append(labels[index][labels[index].find("\n") + 1:])
            sizes.append(pow(i, 1.6))
            values.pop(index)
            labels.pop(index)
    palette = sns.light_palette(color=(210, 90, 60),
                                input="husl",
                                n_colors=len(sorted_labels))
    palette.reverse()
    squarify.plot(sizes=sizes, label=sorted_labels, color=palette)
    plt.axis('off')
    plt.show()
Exemple #4
0
def plotGeoTree():
    labels = []
    for i in geoTypesDisko.index:
        labels.append(geolNamesPlot[i])

    fig, ax = plt.subplots(dpi=200, subplot_kw=dict(aspect="equal"))
    geoTypePerc = list(geoTypesDisko.area_perc)

    squarify.plot(sizes=geoTypePerc, label=labels,
                  color=geolColours)  #,alpha=.4)
    plt.axis('off')
    plt.show()

    p = np.array([0, 6, 3, 7, 2, 1, 5, 4])
    p = p.astype(int)

    geoPerc_ordered = []
    label_ordered = []
    geoCol_ordered = []
    for i in p:
        geoPerc_ordered.append(geoTypePerc[i])
        label_ordered.append(labels[i])
        geoCol_ordered.append(geolColours[i])

    fig2, ax2 = plt.subplots(dpi=200, subplot_kw=dict(aspect="equal"))

    ax2.squarify.plot(sizes=geoPerc_ordered,
                      label=label_ordered,
                      color=geoCol_ordered)  #,alpha=.4)
    ax2.axis('off')
    plt.show()
def visualization(picks_ayz, scores, picks, times, top):
    '''prints sentiment analysis
       makes a most mentioned picks chart
       makes a chart of sentiment analysis of top picks
       
    Parameter:   picks_ayz: int: top picks to analyze
                 scores: dictionary: dictionary of all the sentiment analysis
                 picks: int: most mentioned picks
                times: list: include # of time top tickers is mentioned
                top: list: list of top tickers
    Return:       None
    '''
    
    # printing sentiment analysis 
    print(f"\nSentiment analysis of top {picks_ayz} picks:")
    df = pd.DataFrame(scores)
    df.index = ['Bearish', 'Neutral', 'Bullish', 'Total/Compound']
    df = df.T
    print(df)
    
    # Date Visualization
    # most mentioned picks    
    squarify.plot(sizes=times, label=top, alpha=.7 )
    plt.axis('off')
    plt.title(f"{picks} most mentioned picks")
    #plt.show()
    
    # Sentiment analysis
    df = df.astype(float)
    colors = ['red', 'springgreen', 'forestgreen', 'coral']
    df.plot(kind = 'bar', color=colors, title=f"Sentiment analysis of top {picks_ayz} picks:")
def plot_type_treemap_matplot(type_df, fp="type_treemap_matplot.pdf"):

    type_df = type_df.rename(index={"Merger/Acquisition": "Merger/Acq."})
    type_df = type_df.drop(labels=["None"], axis=0)
    type_df = type_df.sort_values("n", ascending=True)

    type_df["label"] = type_df.apply(
        lambda x: r"$\bf{" + x.name + "}$" +
        f"\n{x['pct']:.1f}% (n={x['n'].astype('int')})",
        axis=1,
    )

    print(type_df)

    figsize = [10, 5.63]
    plt.rcParams["figure.figsize"] = figsize
    cmap = plt.get_cmap("tab20", lut=len(type_df.index))
    # Change color
    fig = plt.figure(figsize=figsize, dpi=300)
    squarify.plot(
        sizes=type_df["n"],
        label=type_df["label"],
        color=cmap.colors,
        alpha=0.4,
        figure=fig,
        pad=True,
    )
    plt.title(
        "Distribution of unit categories in SENTiVENT English corpus.",
        fontsize=12,
        figure=fig,
    )
    plt.axis("off")
    plt.show()
    fig.savefig(fp)
Exemple #7
0
def treemap_plot(x, y):
    word_freq_tuples = most_frequent_words(x, 15)
    word_freq_dict = dict(word_freq_tuples)

    labels = list(word_freq_dict.keys())
    data = list(word_freq_dict.values())

    ####### uncomment the 4 lines below to change the tree plot to classes instead of words
    # counts = Counter(y)
    # sorted(counts.items())
    # labels = 'World', 'Sports', 'Business', 'Sci/Tech'
    # data =list(counts.values())

    colors = [
        plt.cm.Spectral(i / float(len(labels))) for i in range(len(labels))
    ]
    fig = plt.figure(figsize=(12, 8), dpi=80)
    squarify.plot(sizes=data,
                  label=labels,
                  color=colors,
                  alpha=.8,
                  text_kwargs={'fontsize': 20})

    plt.title('Treemap of AG News Class')
    plt.axis('off')
    plt.show()
    fig.savefig('plots/ag_news_treemap.png', format='png', dpi=300)
Exemple #8
0
def plot_treemap(breed_col, animal_type):
    '''
        Creates a treemap of the breeds for each animal type. The large the
        quantity of a given breed, the larger the box.
        Args:
            breed_col (Series): The series contains the breeds as an index and
                the quantity of that breed as the value for the given i.
            animal_type (str): The animal type plotted (e.g., cat, dog, etc.)
        Returns:
            plt
    '''

    colors = [
        '#820fdf', '#0bc7ff', '#f8685f', '#f1b82d', '#df0fd9', '#0fdf35',
        '#f17e24', '#244ff1'
    ]
    fig = plt.figure()

    labels = [
        breed_col.index[i] + ' (' + str(breed_col[i]) + ')'
        for i in range(len(breed_col))
    ]
    squarify.plot(sizes=breed_col, label=labels, color=colors, alpha=.4)
    plt.axis('off')
    plt.rc('font', size=10)
    plt.title(animal_type)
    plt.show()
    fname = animal_type + '_treemap.png'
    fig.savefig(fname, transparent=False)
    plt.close()

    return plt
def plot_tree_map(data, title=None, fig_size=(20, 15), cmap_name=None, filename=None):
    """
    :param data: pd.Series of data
    :param title: Chart title name
    :param fig_size: figure size (default = (20,15)
    :param cmap_name: Specify a custom color map. Default=None
    :param filename: Filename for export chart. If 'None'(Default), no file is exported.
    :return: None
    """

    fig = plt.gcf()
    fig.set_size_inches(fig_size)
    # color scale on the population
    if cmap_name is not None:
        cmap = plt.get_cmap(cmap_name)
        mini, maxi = data.min(), data.max()
        norm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)
        colors = [cmap(norm(value)) for value in data]
        # colors[1] = "#FBFCFE"
    else:
        colors = None

    squarify.plot(sizes=data, label=data.index, alpha=.8, color=colors)
    plt.title(title)
    plt.axis('off')

    if filename is not None:
        plt.savefig(cf.EXPORT_PATH + filename, bbox_inches='tight')
        print(filename + ' exported!')

    plt.show()
    def print_treemap(self, df, fig, ax):
        #ソート
        df = self.rank_sort(df, False)
        #最大文字数検索
        max_num = self.max_word_num(df)

        sns.set()
        matplotlib.rcParams['figure.figsize'] = (16.0, 9.0)
        # ggplot style使用
        style.use('ggplot')
        sns.set(font="IPAexGothic")  #日本語フォント設定

        # Colormap
        cmap = matplotlib.cm.Blues

        # Min and Max Values
        #割合作成後dfに追加
        df = self.add_percent(df)
        mini = min(df["Population"])
        maxi = max(df["Population"])

        # colors setting
        norm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)
        colors = [cmap(norm(value)) for value in df["Population"]]

        # Plotting
        #squarify.plot(sizes=df["Population"], label=df['word'], alpha=0.8, color=colors, text_kwargs={'fontsize':int(100/max_num),'color':'black'})
        squarify.plot(sizes=df["Population"],
                      label=df['word'],
                      alpha=0.8,
                      color=colors)
        # 軸削除
        plt.axis('off')
        # y軸逆に
        plt.gca().invert_yaxis()
Exemple #11
0
def GenreTreeMap():
	print("Be sure to close chart window before continuing")
	db.query("SELECT COUNT(id) as count, SUM(play_count) as pc, genre FROM library GROUP BY genre ORDER BY count DESC LIMIT 20;")

	sizs = []
	labels = []
	plays = []

	for genre in db.rs:
		sizs.append(genre['count'])
		labels.append(genre['genre'])
		plays.append(int(genre['pc']))

	# print(plays)

	# create a color palette, mapped to these values
	cmap = matplotlib.cm.Reds
	mini=min(plays)
	maxi=max(plays)
	norm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)
	colors = [cmap(norm(value)) for value in plays]
	 
	# Change color
	squarify.plot(sizes=sizs,label=labels, alpha=.8)#, color=colors )
	plt.axis('off')
	plt.show()
Exemple #12
0
def make_complaints_leveled(complaints_t1):
    complaints_binned = feat_engineering_helpers.complaint_bins(complaints_t1)
    complaints_binned_g = complaints_binned.groupby(
        'complaints_binned').size().reset_index(name='counts').sort_values(
            ['counts'], ascending=True)
    complaints_binned_g['complaints_pct'] = complaints_binned_g[
        'counts'] / complaints_binned_g['counts'].sum()

    plt.figure(figsize=(15, 10), dpi=80)

    complaints_binned_g['labels'] = complaints_binned_g[
        'complaints_binned'].str.title() + '\n (' + (
            complaints_binned_g['complaints_pct'] * 100).round(2).map(
                '{}%'.format) + ')'
    norm = matplotlib.colors.Normalize(
        vmin=min(complaints_binned_g['complaints_pct']),
        vmax=max(complaints_binned_g['complaints_pct']))
    colors = [
        matplotlib.cm.Blues(norm(value))
        for value in complaints_binned_g['complaints_pct']
    ]
    squarify.plot(sizes=complaints_binned_g['complaints_pct'],
                  label=complaints_binned_g['labels'],
                  color=colors,
                  alpha=1)
    plt.title(
        'COMPLAINTS LEVELED AGAINST CHICAGO POLICE OFFICERS PER COMPLAINT TYPE \n Total number of complaints: {:,} \n Jan. 1, 2012 to Dec. 31, 2014'
        .format(complaints_binned_g['counts'].sum()),
        fontsize=15)
    plt.axis('off')
    plt.savefig('treemap_per_complaint', bbox_inches='tight')
Exemple #13
0
def create_country_plots(participant_dict2, CUTOFF_NUMBER=1):
    country_vec_clean = create_unique_countries(participant_dict2['country'])

    country_df = pd.DataFrame(
        {'Country': list(Counter(country_vec_clean).keys()), 'Count': list(Counter(country_vec_clean).values())})
    country_df['Percentage'] = pd.to_numeric(country_df['Count']) / len(country_vec_clean) * 100
    country_df['Country'] = country_df['Country'].astype(str)
    country_df = country_df.loc[country_df['Country'] != 'No Data',]  # TODO
    number_other_countries = country_df.loc[country_df['Percentage'] <= CUTOFF_NUMBER,]
    country_df = country_df.loc[country_df['Percentage'] > CUTOFF_NUMBER,]
    country_df = country_df.append({'Country': 'Other Countries',
                                    'Count': number_other_countries['Count'].sum(),
                                    'Percentage': number_other_countries['Percentage'].sum()}, ignore_index=True)
    country_df = country_df.sort_values(['Percentage'], ascending=False).reset_index(drop=True)

    # TREEMAP PLOT
    mpl.rcParams['text.color'] = 'white'
    c = sns.color_palette("YlGnBu", 40)[26:]
    squarify.plot(sizes=country_df['Count'],
                  label=country_df['Country'] + '\nCount=' + country_df['Count'].astype(str),
                  alpha=.95,
                  color=c[::-1])
    plt.axis('off')
    plt.title('Participants Countries of Origin')
    plt.savefig(os.getcwd() + '/participant_figures/countries_treemap.png')
    plt.show()

    # BARPLOT
    # ax = sns.barplot(x="Country", y='Percentage', data=country_df, color=(0.2, 0.4, 0.6, 0.6))
    # plt.xticks(rotation=35)
    # plt.savefig(os.getcwd() + '/participant_figures/countries_hist.pdf')
    # plt.show()
    return country_df
Exemple #14
0
    def portfolio_tree_plot(self, days_lookup):

        cum_last_return = self.stocks_gains.tail(days_lookup).add(
            1).cumprod().tail(1).add(-1).multiply(100).iloc[0, :]

        weights = self.portfolio_weights.tail(days_lookup).mean()

        df = pd.concat([cum_last_return, weights], axis=1)
        df.columns = ['ganhos', 'pesos']
        df = df[df.pesos > 0].sort_values('ganhos')

        volume = df.pesos.values.tolist()
        labels = [
            f'{x}\n{y}%' for x, y in zip(df.index.values,
                                         df.ganhos.round(1).values.tolist())
        ]
        color_list = [
            '#D30000' if x < 0 else '#3BB143'
            for x in df.ganhos.round(1).values.tolist()
        ]

        plt.figure(figsize=(10, 7))
        plt.rc('font', size=14)
        squarify.plot(sizes=volume,
                      label=labels,
                      color=color_list,
                      alpha=0.7,
                      edgecolor="white",
                      linewidth=3)

        plt.axis('off')

        plt.show()

        return True
Exemple #15
0
def treemap_value(year=2019):

    df_mp_v = df_mp[df_mp["REF_DATE"] == year]
    df_mp_v = df_mp_v[["Region", "Country", "VALUE"]].groupby(by=["Region", "Country"]).sum()
    df_mp_v = df_mp_v.reset_index().sort_values(by="VALUE", ascending=False)
    df_mp_v

    import squarify
    import numpy as np

    colors = ["#98eff9" if region == "Pacific" else "#ffcfdc" for region in df_mp_v["Region"]]
    labels = [f"{country}\n${round(value/1000000, 1)} B" for country, value in zip(df_mp_v["Country"], df_mp_v["VALUE"])]
    size = round(np.sqrt(df_mp_v["VALUE"].sum() / 1000000), 0)

    fig, ax = plt.subplots(figsize=(size*1.2, size*0.8))
    squarify.plot(
        df_mp_v["VALUE"],
        color=colors,
        label=labels,
        ax=ax,
        alpha=1,
        bar_kwargs=dict(linewidth=1, edgecolor="#ffffff"),
        text_kwargs={"fontsize": 8}
    )

    ax.axis("off")
    ax.set_title(f"Canadian Exportation Volumes to Major Eastern / Western Coast Partners in {year}", fontsize=12)

    plt.show()
def k_means(data, size, file_path):
    # Performing k_means clustering algorithm for all pixels' RGB of the image:
    kmeans = KMeans(n_clusters=size).fit(data)
    centroids = kmeans.cluster_centers_
    cluster_colors = [(int(a[0]), int(a[1]), int(a[2])) for a in centroids]
    cluster_hex_colors = ['#%02x%02x%02x' % i for i in cluster_colors]
    sizes = Counter(kmeans.labels_).values()

    # Plot Histogram from clusters:
    plt.bar(cluster_hex_colors, sizes, color=cluster_hex_colors)
    plt.xticks(rotation='vertical')
    plt.show()

    # Plot TreeMap with labels of clusters:
    plt.rc('font', size=14)
    plt.figure(figsize=(15, 15))
    plt.suptitle(file_path, fontsize=20)
    squarify.plot(sizes=sizes, label=cluster_hex_colors,
                  color=cluster_hex_colors, alpha=0.7)
    plt.axis('off')
    plt.show()

    # Plot TreeMap without labels of clusters
    plt.rc('font', size=14)
    plt.figure(figsize=(15, 15))
    squarify.plot(sizes=sizes,
                  color=cluster_hex_colors, alpha=0.7)
    plt.axis('off')
    plt.show()
Exemple #17
0
def creat_tile_for_twenty_most_common(twenty_most_common):
    volume = [x[1] for x in twenty_most_common]
    labels = [x[0] for x in twenty_most_common]
    color_list = [
        '#0f7216', '#b2790c', '#ffe9a3', '#f9d4d4', '#d35158', '#ea3033'
    ]
    squarify.plot(sizes=volume, label=labels, color=color_list, alpha=0.7)
    plt.show()
def show_treemap(stats: EmployeeStatistics) -> None:
    """ Displays a treemap chart of salaries and ages to help determine if 
    there is any ageism implanted into the corporate policy of selecting
    positions and salaries """
    squarify.plot(sizes=list(map(lambda x: x['salary'], stats.salary_age_group())),
        label=list(map(lambda x: x['age'], stats.salary_age_group())), alpha=.7)
    plt.axis('off')
    plt.show()
def saveTreeMap(lista, imgname):
    cantidad = []
    key = []
    for i in lista:
        key.append(i[0])
        cantidad.append(i[1])
    squarify.plot(sizes=cantidad, label=key, alpha=.8)
    plt.axis('off')
    plt.title(imgname, fontsize=20, fontweight="bold")
    plt.savefig(imgname)
Exemple #20
0
def plot_gp_distribution(dist, leaf):
    sizes = []
    labels = []
    for k, v in leaf.items():
        if v:
            sizes.append(dist[k])
            labels.append(k)
    plt.figure(figsize=(8, 6))
    squarify.plot(sizes=sizes, label=labels)
    plt.show()
Exemple #21
0
def plot_treemap_with_counts(x, min_counts, use_percentages=False, figsize=(9, 6)):
    plt.figure(figsize=figsize)
    x_counts = truncate_counts(x.value_counts(), min_counts)
    if use_percentages:
        x_counts_str = (100 * (x_counts / x_counts.sum())).round(1).apply("{}%".format)
    else:
        x_counts_str = x_counts.apply(str)
    labels = x_counts.index + "\n" + x_counts_str
    squarify.plot(x_counts.values, label=labels)
    plt.axis("off")
Exemple #22
0
    def treemap(w=w):

        plt.rcParams.update({'font.size': 22})

        plt.figure(figsize=(25, 15))

        squarify.plot(sizes=extension_sizes[:w].values,
                      label=extension_sizes[:w].index.values)
        plt.title('Extension Treemap by Size')
        plt.axis('off')
Exemple #23
0
def treeMap(summarize, product, Title='Tree Map'):
    # Change color
    dfPolar = summarize[summarize.asin == product]
    colorRB = plt.cm.rainbow(np.linspace(0, 1, len(dfPolar)))
    squarify.plot(sizes=list(dfPolar.summary),
                  label=list(dfPolar.levels),
                  color=colorRB,
                  alpha=.4)
    plt.title(Title + ' product :' + product)
    plt.axis('off')
    plt.show()
def plot_top_tokens(token_sets):
    summary_table = summarize(token_sets)
    top_tokens_table = summary_table[summary_table["rank"] <= 20]
    print("PLOTTING TOP TOKENS...")

    #sns.distplot(summary_table["pct"])
    #plt.show()

    squarify.plot(sizes=top_tokens_table["pct"], label=top_tokens_table["token"], alpha=0.8)
    plt.axis("off")
    plt.show()
def tree_map_top(c):
    final_stats = get_page_rank_statistic(c, 20)
    final_page_ranks = []
    for i in range(len(final_stats)):
        final_page_ranks.append(final_stats[i][1])
    final_titles = []
    for i in range(len(final_stats)):
        final_titles.append(final_stats[i][0])
    squarify.plot(sizes=final_page_ranks, label=final_titles, alpha=.7)
    plt.axis('off')
    plt.show()
 def plot(self):
     ''' plot some random stuff '''
     squarify.plot(sizes=[13, 22, 35, 5],
                   label=["group A", "group B", "group C", "group D"],
                   alpha=.7)
     # plt.axis('off')
     # plt.show()
     # data = [random.random() for i in range(25)]
     # ax = self.figure.add_subplot(111)
     # ax.hold(False)
     # ax.plot(data, '*-')
     self.canvas.draw()
def plot_treemap(reduction_percentages, labels, title):
    colors = [
        plt.cm.Spectral(i / float(len(reduction_percentages)))
        for i in range(len(reduction_percentages))
    ]
    plt.figure(figsize=(9, 8), dpi=120)
    squarify.plot(sizes=reduction_percentages,
                  label=labels,
                  alpha=.6,
                  color=colors)
    plt.title(title, fontsize=16, fontweight="medium")
    plt.axis('off')
Exemple #28
0
    def treemap(self, df, col, labels, plot_title):
        """Treemap plot for well logs data

        Visualization that split the area of chart to display the value of datapoints presence in dataframe.  
        A column called "LABELS" will be created that show the wells with number of datapoints below it.

        Parameters
        ----------
        df : str
            Well logs dataframe; lasFile_impt_df
        col : str
            Column that have no missing values, to acquire the count of datapoints
        labels : str
            String columns
        plot_title : str
            Title of the diagram
        
        Returns
        -------
        fig : object
            Chart
        """
        temp_df = df.groupby('WELL').count()
        temp_df = temp_df.reset_index()
        temp_df['LABELS'] = temp_df['WELL'].str.replace(
            'SUMANDAK', 'SMDK') + '\n' + temp_df['DEPTH'].astype(str)
        temp_df['DEPTH'] = temp_df['DEPTH'].astype(int)
        temp_df = temp_df.sort_values(by=['DEPTH'], ascending=False)
        temp_df = temp_df.reset_index(drop=True)

        norm = matplotlib.colors.Normalize(vmin=min(temp_df[col]),
                                           vmax=max(temp_df[col]))
        colors = [matplotlib.cm.Greens(norm(value)) for value in temp_df[col]]

        fig = plt.gcf()
        ax = fig.add_subplot()
        fig.set_size_inches(30, 20)

        squarify.plot(sizes=temp_df[col],
                      label=temp_df[labels],
                      color=colors,
                      alpha=0.7,
                      text_kwargs={'fontsize': 16})
        plt.title(plot_title + '\n' +
                  'Total Observations: {}'.format(str(df.shape[0])),
                  fontsize=23,
                  fontweight="bold")
        plt.axis('off')
        plt.gca().invert_yaxis()
        plt.show()

        return fig
Exemple #29
0
def return_blocks(returns):

    sret = (returns.sum()[returns.sum() > 0]).mul(100).round(0)

    cmap = cm.YlGn
    mini = min(sret)
    maxi = max(sret)
    norm = cm.colors.Normalize(vmin=mini, vmax=maxi)
    colors = [cmap(norm(value)) for value in sret]

    squarify.plot(sizes=sret, label=sret.index, alpha=.8, color=colors)
    plt.axis('off')
    plt.show()
Exemple #30
0
def draw_treemap(feature_name, count):
    set_font()
    squarify.plot(sizes=count, label=feature_name, alpha=0.4)
    
    plt.axis("off")
    
    # 현재 폴더에 tdf_treemap.png 파일명으로 저장, dpi는 그림 해상도 지정 
    # bbox_inches='tight'는 그림을 둘러싼 여백 제거 
    pic_IObytes = io.BytesIO()
    plt.savefig(pic_IObytes,  format='png')
    pic_IObytes.seek(0)
    pic_hash = base64.b64encode(pic_IObytes.read())
    print(pic_hash)
Exemple #31
0
def genre_map(genre_counts, genre_list, name, th):

    """Generates a treemap of the genres/moods in a dataset, with the corresponding percentage for each genre/mood.

    Args:
        genre_counts (pandas.Series object): Contains the different unique genres/moods as keys and the counts for each one as values.
        genre_list (list): Contains the list of all the genres/moods, each element corresponds to a recording in the dataset.
        name (str): Name of the dataset, to display as a title.
        th (int): Threshold to only show cattegories that have a percentage above that. If th=0 it shows all the cattegories. 

    """

    if len(genre_list) == 0:
        raise TypeError('genre_list can\'t be an empty list')
        return
    
    # Creating colorscheme
    cmap = cm.Blues
    mini=min(np.array(genre_counts))
    maxi=max(np.array(genre_counts))
    norm = clr.Normalize(vmin=mini, vmax=maxi)
    colors = [cmap(norm(value)) for value in np.array(genre_counts)]

    other = 0
    x = np.array(genre_counts)
    y = np.array(genre_counts.keys())

    if th > 0:
        for el in x:
            
            pct = 100*el/float(len(genre_list))
            
            if pct < th:
                other += el
                i = np.where(x == el)
                x = np.delete(x, i, 0)
                y = np.delete(y, i, 0)
                
        x = np.append(x, other)
        y = np.append(y, 'other')

    squarify.plot(sizes=x, label=y, alpha=.8, color=colors)
    plt.axis('off')
    plt.title(name)
    plt.show() 
Exemple #32
0
def download():
    import squarify

    values = sorted([i ** 3 for i in range(1, 50)], reverse=True)

    cmap = mlp.cm.Spectral
    norm = mlp.colors.Normalize(vmin=min(values), vmax=max(values))
    colors = [cmap(norm(value)) for value in values]

    fig = plt.figure(1)
    ax = fig.add_subplot(111)
    squarify.plot(sizes=values, alpha=.8, color=colors, ax=ax)
    ax.axis("off")

    buf = BytesIO()
    fig.canvas.print_figure(buf, format='svg')

    headers = {
        'Content-Type': 'image/svg+xml',
        'Content-Disposition': 'attachment; filename="graph.svg"',
    }
    return http.Response(buf.getvalue(), headers=headers)
Exemple #33
0
import matplotlib as mlp
import matplotlib.pyplot as plt
import squarify

values = sorted([i ** 3 for i in range(1, 50)], reverse=True)

cmap = mlp.cm.Spectral
norm = mlp.colors.Normalize(vmin=min(values), vmax=max(values))
colors = [cmap(norm(value)) for value in values]

squarify.plot(sizes=values, alpha=.8, color=colors)
plt.axis('off')
plt.show()
Exemple #34
0
        type2 = i.split('-')
        for j in range(len(type2)):
            if type2[j] == item:
                num += 1
            else:
                continue
    dom2.append(num)
# 数据创建
data = {'tags': tags, 'num': dom2}
frame = pd.DataFrame(data)
df1 = frame.sort_values(by='num', ascending=False)
name = df1['tags'][:10]
income = df1['num'][:10]
# 绘图details
colors = ['#993333', '#CC9966',  '#333333', '#663366', '#003366', '#009966', '#FF6600', '#FF0033', '#009999', '#333366']
plot = squarify.plot(sizes=income, label=name, color=colors, alpha=1, value=income, edgecolor='white', linewidth=1.5)
# 设置图片显示属性,字体及大小
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['font.size'] = 8
plt.rcParams['axes.unicode_minus'] = False
# 设置标签大小为1
plt.rc('font', size=6)
# 设置标题大小
plot.set_title('网易云音乐华语歌单标签图', fontsize=13, fontweight='light')
# 除坐标轴
plt.axis('off')
# 除上边框和右边框刻度
plt.tick_params(top=False, right=False)
# 图形展示
plt.show()