Пример #1
0
def piecharts(request):
	allEntries = Entry.objects.all().filter(created_by__username=request.user.username)
	seasons = split_by_season(allEntries)
	seasons_name = ["spring", "fall", "winter", "summer", "current month"]
	labels = ["negative", "neutral", "positive"]
	chart_list = []
	for i in range(len(seasons)):
		if (seasons[i][0] != 0):
			data = [Pie(labels=labels, values=seasons[i])]
			layout = Layout(title=seasons_name[i])
			chart_list.append(plot(dict(data=data, layout=layout), output_type='div'))
	times = split_by_time(allEntries)
	times_name = ["morning", "afternoon", "evening", "night"]
	for i in range(len(times)):
		if (times[i][0] != 0):
			data = [Pie(labels=labels, values=times[i])]
			layout = Layout(title=times_name[i])
			chart_list.append(plot(dict(data=data, layout=layout), output_type='div'))
	days = split_by_day(allEntries)
	days_name = ["weekday", "weekend"]
	for i in range(len(days)):
		if (days[i][0] != 0):
			data = [Pie(labels=labels, values=days[i])]
			layout = Layout(title=days_name[i])
			chart_list.append(plot(dict(data=data, layout=layout), output_type='div'))
	return render(request, "piecharts.html", {"all_charts": chart_list})
Пример #2
0
def return_graphs(df):
    """Creates  plotly visualizations
    Args:
        df - Schema name 
    Returns:
        list (dict): list containing the four plotly visualizations

    """
    col_list = [
        'floods', 'storm', 'fire', 'earthquake', 'cold', 'other_weather'
    ]

    # Get rows with weather_related only
    weather_related = (df["weather_related"] == 1)
    df_weather = df[weather_related]

    #Get dataframe with weather related messages only
    weather_data = get_categ_cnt(df_weather, col_list, 'Weather_Category',
                                 'count')
    weather_cat = weather_data['Weather_Category'].tolist()
    count = weather_data['count'].tolist()

    #Get weather related death only
    weather_related_death = (df["death"] == 1) & (df["weather_related"] == 1)
    df_new = df[weather_related_death]
    weather_death = get_categ_cnt(df_new, col_list, 'Weather_Category',
                                  'Death_count')

    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    graphs = [{
        'data': [
            Bar(x=weather_death.Weather_Category.tolist(),
                y=weather_death.Death_count.tolist())
        ],
        'layout': {
            'title':
            'Bar chart to show death counts for various Weather Conditions ',
            'yaxis': {
                'title': "Death Count"
            },
            'xaxis': {
                'title': "Weather Conditions"
            }
        }
    }, {
        'data': [Pie(labels=weather_cat, values=count)],
        'layout': {
            'title':
            'Pie Chart to show break down by Various Weather related conditions'
        }
    }, {
        'data': [Pie(labels=genre_names, values=genre_counts)],
        'layout': {
            'title': 'Pie Chart to show message Break-down by Genre'
        }
    }]

    return graphs
Пример #3
0
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    category_counts = list(df[category_columns].sum())
    category_names = [c.replace('_', ' ').capitalize() for c in category_columns]

    print(type(category_counts))
    print(type(category_names))

    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [
        {
            'data': [
                Pie(
                    labels=category_names,
                    values=category_counts
                )
            ],

            'layout': {
                'title': 'Distribution of Categories',
                'yaxis': {
                    'title': "Count"
                }
            }
        },
        {
            'data': [
                Pie(
                    labels=genre_names,
                    values=genre_counts
                )
            ],

            'layout': {
                'title': 'Distribution of Message Genres',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                }
            }
        }
    ]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #4
0
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    cat_names = df.columns[4:]
    cat_sums = df.sum()[cat_names]
    total = sum(cat_sums)
    small_sums = [cat for cat in cat_sums.values if cat < 0.1 * total]

    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [
        {
            'data': [
                Pie(labels=cat_names,
                    values=cat_sums,
                    insidetextfont={'size': 1})
            ],
            'layout': {
                'title': 'Distribution of Message Categories',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                }
            }
        },
        {
            'data': [Pie(labels=genre_names, values=genre_counts)],
            'layout': {
                'title': 'Distribution of Message Genres'
            }
        },
        {
            'data': [
                Table(header=dict(values=['id', 'message', 'genre']),
                      cells=dict(values=[df.id, df.message, df.genre]))
            ],
            'layout': {
                'title': 'Messages Table'
            }
        },
    ]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #5
0
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    # get the counts of messages against each label and category
    cat_counts = df.filter(
        df.columns[4:7].tolist()).sum().sort_values(ascending=False)
    cat_names = list(cat_counts.index)

    label_counts = df.filter(
        df.columns[7:].tolist()).sum().sort_values(ascending=False)
    label_names = list(label_counts.index)
    # print(df.columns[4:].str.title())

    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [{
        'data': [Pie(labels=genre_names, values=genre_counts)],
        'layout': {
            'title': 'Distribution of Message Genres'
        }
    }, {
        'data': [Pie(labels=cat_names, values=cat_counts)],
        'layout': {
            'title': 'Distribution of Label Categories'
        }
    }, {
        'data': [Bar(x=label_names, y=label_counts)],
        'layout': {
            'title': 'Distribution of Message Labels',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Labels"
            }
        }
    }]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #6
0
def create_fig():
    #方程作用:建立两个Graphes
    #输入:无
    #输出 list(dict):含有两个Graphes
    #Graph 1
    genre_names = df.columns[4:39].tolist()
    genre_counts = df[genre_names].sum(axis=0)
    graph_one = [Bar(x=genre_names, y=genre_counts)]

    layout_one = Layout(title='Message distribution by types',
                        xaxis=dict(title='Message Types'),
                        yaxis=dict(title='Message Number'),
                        barmode='overlay',
                        showlegend=False)
    #figure 2
    labels = genre_names
    values = genre_counts
    graph_two = [Pie(labels=labels, values=values)]
    layout_two = Layout(title='Percentage of message number by type')

    figures = [
        Figure(data=graph_one, layout=layout_one),
        Figure(data=graph_two, layout=layout_two)
    ]

    return figures
Пример #7
0
def make_diagram_plot(proba, wav_file_name):
    labels, values = [
        emotions_map[i + 1] for i in xrange(len(emotions_map.keys()))
    ], 100 * proba
    print labels, values
    trace = Pie(labels=labels, values=values)
    plot([trace], filename='diagram-for-' + '_'.join(wav_file_name.split('.')))
Пример #8
0
def index():

    # extract data needed for visuals

    labels_counts = df.iloc[:,4:].sum().sort_values(ascending=False)
    
    labels_names = labels_counts.index.values

    genre_counts = df.groupby("genre").count()["message"]
    genre_names = list(genre_counts.index)

    # create visuals
    graphs = [
        {
            "data": [Bar(x=labels_names, y=labels_counts)],
            "layout": {
                "title": "Distribution of Message Categories",
                "yaxis": {"title": "Count"},
                "xaxis": {"title": "\r\n\n\n Categorie"},
            },
        },
        {
            "data": [Pie(labels=genre_names, values=genre_counts)],
            "layout": {
                "title": "Distribution of Message Genres",
            },
        },
    ]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template("master.html", ids=ids, graphJSON=graphJSON)
Пример #9
0
def biom_pie_plot(values, labels):
    trace1 = Pie(values=values,
                 labels=labels,
                 name="Section's Employees count",
                 textinfo='label+value'
                 # hoverinfo= "label+value+percent+name",
                 # hole=0.2
                 )
    data = [trace1]
    layout = dict(
        title="Section's Employees count",
        # annotations= [
        #     dict(
        #         font= {"size": 20},
        #         showarrow= False,
        #         text= "Section's Employees count",
        #         x= 0.5,
        #         y= 0.5
        #         )
        #     ]
    )

    fig = dict(data=data, layout=layout)
    py.offline.plot(fig,
                    filename='Section_Employees_count.html',
                    auto_open=False)
Пример #10
0
def index():

    #extract data needed for visuals

    #genre
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    #Message categories
    category_counts = df.drop(['id', 'message', 'original', 'genre'],
                              axis=1).sum().sort_values(ascending=False)
    category_names = list(category_counts.index)[0:10]

    #News media categories
    news = df[df['genre'] == 'news']
    news_counts = news.drop(['id', 'message', 'original', 'genre'],
                            axis=1).sum().sort_values(ascending=False)
    news_cat = list(news_counts.index)[0:10]
    #Create visuals
    graphs = [{
        'data': [Bar(x=genre_names, y=genre_counts)],
        'layout': {
            'title': 'Distribution of Message Genres',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Genre"
            }
        }
    }, {
        'data': [Bar(x=category_names, y=category_counts)],
        'layout': {
            'title': 'Distribution of top 10 Message Categories',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Category"
            }
        }
    }, {
        'data': [Pie(labels=news_cat, values=news_counts[0:10])],
        'layout': {
            'title': 'News Media - Distribution of top 10 Message Categories',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Category"
            }
        }
    }]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #11
0
def Profit(request):
    p = Order.objects.all().filter(p_id=post_id(request)).values('o_profit')
    order = list(p)
    total = 0
    for i in order:
        total += i['o_profit']
    Category_Profit = float(total)

    p0 = Order.objects.all().values('o_profit')
    order0 = list(p0)
    total1 = 0
    for i in order0:
        total1 += i['o_profit']
    Total_Profit = float(total1)
    proportion = 100 * Category_Profit / Total_Profit
    per = Category_Profit / Total_Profit
    l = []
    l.append('other products')
    l.append(post_id(request))
    value = []

    value.append(1 - per)
    value.append(per)
    plot_div = plot([Pie(labels=l, values=value)], output_type='div')

    #下拉選單
    allp = Order.objects.values('p_id').distinct()
    return render(request, 'profit.html', locals())
Пример #12
0
def marketing(request):
    #request.POST.get('select_pid')
    #算歷年單一產品總品類佔有率
    allorder = Order.objects.values('p_id').distinct()
    rev = Order.objects.all().filter(p_id=sel_id(request)).values('o_quantity')
    return_id = str(sel_id(request))
    #values 取欄位名稱
    orderlist = list(rev)
    total = 0
    for i in orderlist:
        total += i['o_quantity']
        #逐項加總
    category_sales = float(total)

    full = random.randint(1000, 1200)
    proportion = 100 * category_sales / full
    proportion = round(proportion, 4)
    zara = random.randint(9, 28)
    hm = random.randint(7, 14)
    l = []
    l.append('others')
    l.append('ZARA')
    l.append('H&M')
    # l.append(sel_id(request))
    l.append('Uniqlo')
    value = []

    value.append(100 - proportion - zara - hm)
    value.append(zara)
    value.append(hm)
    value.append(proportion)
    plot_div = plot([Pie(labels=l, values=value)], output_type='div')
    #假設該品類銷售總量 100000
    return render(request, 'marketing.html', locals())
def return_figures():
    """Creates two plotly visualizations

    Args:
        None

    Returns:
        list (dict): list containing the two plotly visualizations

    """
    # Creates a pie chart of the source of training data
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    data_one = [Pie(labels=genre_names, values=genre_counts)]
    layout_one = dict(title='Source of Training Data (Genre)')

    # Creates a bar chart of the distribution of categories
    cat_df = df.drop(['id', 'message', 'original', 'genre'], axis=1)
    cat_names = list(cat_df.columns.values)
    cat_counts = cat_df.sum()

    data_two = [Bar(x=cat_names, y=cat_counts)]
    layout_two = dict(title='Distribution of Categories in Training Data',
                      xaxis=dict(title='Categories'),
                      yaxis=dict(title='Count'))

    # append all charts to the figures list
    figures = []
    figures.append(dict(data=data_one, layout=layout_one))
    figures.append(dict(data=data_two, layout=layout_two))

    return figures
Пример #14
0
def create_fig():
    """create two plotly figures
    Args:
        None
       Returns:
        list(dict):list containing the two plotly visualizations
     """
    #figure 1
    genre_names = df.columns[4:39].tolist()
    genre_counts = df[genre_names].sum(axis=0)
    graph_one = [Bar(x=genre_names, y=genre_counts)]

    layout_one = Layout(title='Distribution of Message Types',
                        xaxis=dict(title='Types'),
                        yaxis=dict(title='Count'),
                        barmode='overlay',
                        showlegend=False)
    #figure 2
    labels = genre_names
    values = genre_counts
    graph_two = [Pie(labels=labels, values=values)]
    layout_two = Layout(title='Percentage of All Message Types')

    figures = [
        Figure(data=graph_one, layout=layout_one),
        Figure(data=graph_two, layout=layout_two)
    ]

    return figures
 def plot(self):
     """
     Reads the data frame and plots the necessary visualization
     :returns: Plotly plots
     """
     y = self.df["Churn"].value_counts()
     _layout = Layout(title='Churn')
     _data = Pie(labels = self.df['Churn'].unique(), values=y.values.tolist())
     fig = Figure(data=[_data], layout=_layout)
     fig.show()
     
     fig = px.box(self.df, x="Contract", y="MonthlyCharges")
     fig.show()
     
     fig = px.scatter(self.df, x="tenure", y="MonthlyCharges", 
              color='Churn',
              facet_col="Contract", facet_col_wrap=3,
              title= "Churn Rate Analysis")
     fig.show()
     
     fig = px.scatter(self.df, 
              x="tenure", y="MonthlyCharges", 
              color="Churn", 
              marginal_y="rug", marginal_x="histogram")
     fig.show()
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    category_names = list(df.iloc[:, 4:].sum().index)
    features = category_names + list(['genre'])
    df_new = df[features].groupby('genre').sum().reset_index()
    df_unpivot = pd.melt(df_new, id_vars=['genre'], value_vars=category_names)
    df_unpivot = df_unpivot.sort_values(by=['value'], ascending=False)

    category_names = [c.replace('_', '')
                      for c in category_names]  # remove '_' in name
    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [
        {
            'data': [
                Pie(
                    labels=genre_names,
                    values=genre_counts
                )
            ],

            'layout': {
                'title': 'Distribution of Message Genres',
                'xaxis': {
                    'title': "Genre"
                }
            }
        },

        {
            'data': [
                Bar(name='social', x=category_names, \
                    y=list(df_unpivot.loc[df_unpivot['genre']=='social','value'].values)),
                Bar(name='direct', x=category_names, \
                    y=list(df_unpivot.loc[df_unpivot['genre']=='direct','value'].values)),
                Bar(name='news', x=category_names, \
                    y=list(df_unpivot.loc[df_unpivot['genre']=='news','value'].values))
            ],

            'layout': {
                'title': 'Distribution of Message Categories',
                'yaxis': {
                    'title': "Count"
                },
                'barmode': 'stack'
            }
        }
    ]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #17
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        verspaeti_data_cache = cache.get('verspaeti_data')
        if verspaeti_data_cache is not None:
            colors = ['#63a615', '#ec0016']
            labels = ['Pünktlich', 'Zu spät']
            values = [
                verspaeti_data_cache['num_current_journeys'] -
                verspaeti_data_cache['num_delayed_journeys'],
                verspaeti_data_cache['num_delayed_journeys']]
            plot_div = plot(
                [Pie(
                    labels=labels,
                    values=values,
                    marker=dict(colors=colors))],
                output_type='div')

            context['plot_div'] = plot_div
            context['journeys_delayed'] = verspaeti_data_cache['num_delayed_journeys'],
            context['biggest_delay_name'] = verspaeti_data_cache['biggest_delay_name']
            context['biggest_delay_time'] = verspaeti_data_cache['biggest_delay_time']
            context['average_delay'] = verspaeti_data_cache['average_delay']
        else:
            context['error_message'] = "Wir rechnen noch gerade die Statistiken zusammen, bitte versuche es in ein paar Minuten erneut. Wenn das Problem bestehen bleibt, melde dich bitte per E-Mail an bug_web<at>fahrplandatengarten.de"
        return context
Пример #18
0
def index():
    
    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)
    
    #add visual
    category_names = df.iloc[:,4:].columns
    category_boolean = (df.iloc[:,4:] != 0).sum().values
    
    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [
        {
            'data': [
                Pie(
                    labels=genre_names,
                    values=genre_counts
                )
            ],

            'layout': {
                'title': 'Distribution of Message Genres',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                }
            }
        },
        # GRAPH 2 - category graph    
        {
            'data': [
                Bar(
                    x=category_names,
                    y=category_boolean
                )
            ],

            'layout': {
                'title': 'Distribution of Message Categories',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Category",
                    'tickangle': 30
                }
            }
        }
    ]
    
    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)
    
    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #19
0
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    #extract count of categories
    category = list(df.columns[4:])
    category_counts = [np.sum(df[col]) for col in category]

    # extract mean for percentage
    categories = df.iloc[:, 4:]
    categories_mean = categories.mean().sort_values(ascending=False)[1:11]
    categories_names = list(categories_mean.index)

    # create visuals
    graphs = [{
        'data': [Bar(x=genre_names, y=genre_counts)],
        'layout': {
            'title': 'Distribution of Message Genres',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Genre"
            }
        }
    }, {
        'data': [Bar(x=category, y=category_counts)],
        'layout': {
            'title': 'Distribution of Message Categories',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Category"
            }
        }
    }, {
        'data': [Pie(labels=categories_names, values=categories_mean)],
        'layout': {
            'title': 'Top 10 Message Categories',
            'yaxis': {
                'title': "Percentage"
            },
            'xaxis': {
                'title': "Categories"
            }
        }
    }]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    #df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #20
0
def classify(request):
    record = FraudDetectCount.objects.all()
    fp_sum = 0
    f_sum = 0
    n_sum = 0
    file_count = len(record)
    for i in record:
        fp_sum = fp_sum + i.FalsePos
        f_sum = f_sum + i.Suspicious
        n_sum = n_sum + i.NewCust

    plot_div1 = plot([
        Pie(labels=['FP Detected', 'Suspicious', 'New Customer'],
            values=([fp_sum, f_sum, n_sum]),
            name='test',
            opacity=0.8)
    ],
                     output_type='div')

    context = {
        'fp_sum': fp_sum,
        'f_sum': f_sum,
        'n_sum': n_sum,
        'file_count': file_count,
        'plot_div1': plot_div1
    }
    return render(request, 'CFD_ML/model.html', context)
Пример #21
0
def index():

    # extract data needed for visuals

    type_counts = df.iloc[:, 4:].sum()
    top10 = type_counts.sort_values(ascending=False)[:10]
    type_names = top10.index.tolist()
    type_names = [label.replace("_", " ") for label in type_names]

    # create visuals

    graphs = [{
        'data': [
            Pie(labels=type_names,
                values=top10,
                hoverinfo='label+percent',
                textinfo='value')
        ],
        'layout': {
            'title': 'Top ten type of disaster message '
        }
    }]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #22
0
def index():
    """
    Renders master.html with plotly graphs
    """
    # extract data needed for visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)
    message_counts = df.iloc[:, 4:].sum(axis=0)
    message_counts.sort_values(inplace=True, ascending=False)
    # create visuals
    graph1 = {
        'data': [Pie(labels=genre_names, values=genre_counts)],
        'layout': {
            'title': 'Distribution of Message Genres',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Genre"
            }
        }
    }

    graph2 = {
        'data': [
            Pie(labels=message_counts.index.tolist(),
                values=message_counts.values.tolist())
        ],
        'layout': {
            'title': 'Types of messages received',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Message Type"
            }
        }
    }
    graphs = []
    graphs.append(graph1)
    graphs.append(graph2)
    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #23
0
def index():
    
    # extract data needed for visuals
#     genre_counts = df.groupby('genre').count()['message']
#     genre_names = list(genre_counts.index)
    
    
    # extract data needed for visuals
    sorted_cat = df.iloc[:, 4:].sum(axis=0).sort_values()
    
    plot_categ_values = sorted_cat.tolist()
    plot_categ_names = sorted_cat.index.tolist()
    
    # create visuals
    graphs = [

        {
            'data': [
                Pie(
                    values=plot_categ_values,
                    labels=plot_categ_names,
                   
                )
            ],

            'layout': {
                'title': 'Training Messages Distribution'
            }
        }
    ]    
    
    
#     graphs = [
#         {
#             'data': [
#                 Bar(
#                     x=genre_names,
#                     y=genre_counts
#                 )
#             ],

#             'layout': {
#                 'title': 'Distribution of Message Genres',
#                 'yaxis': {
#                     'title': "Count"
#                 },
#                 'xaxis': {
#                     'title': "Genre"
#                 }
#             }
#         }
#     ]
    
    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)
    
    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #24
0
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    s = df.sum(axis=0,
               numeric_only=True)[1:].sort_values(ascending=False).head(10)
    top10_categories = list(s.index)
    top10_val = list(s.values)

    # Display graph showing top 10 categories

    graphs = [
        {
            'data': [Bar(x=top10_categories, y=top10_val)],
            'layout': {
                'title': {
                    'text': 'Distribution of Top Ten Categories',
                    'font': {
                        'size': '35',
                        'color': '#0066CC'
                    }
                },
                'margin': {
                    'b': 100
                },
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Categories"
                }
            }
        },

        # Display Pie chart for Genre
        {
            'data': [Pie(labels=genre_names, values=genre_counts)],
            'layout': {
                'title': {
                    'text': 'Message Classification by Genre',
                    'font': {
                        'size': '35',
                        'color': '#0066CC'
                    }
                },
                'automargin': True
            }
        }
    ]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #25
0
def index():
    """Index function to generate visualizations."""
    
    # extract data needed for visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)
    
    category_names = df.columns.values[4:]
    categories = df[df.columns[4:]]
    message_cat_perc = (categories.sum(axis = 0)*(100/len(df))).sort_values(ascending=False)
    
    
    # create visuals
    graphs = [
        {
            'data': [
                Bar(
                    x=genre_names,
                    y=genre_counts
                )
            ],

            'layout': {
                'title': 'Distribution of Message Genres',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                }
            }
        },
        {
            'data': [
                Bar(x=message_cat_perc,y=category_names, orientation='h')
            ],
             'orientation' : 'h',
            'layout': {
                'title': 'Percentage of Messages/Category',
                'yaxis': {'title': "Category"},
                'xaxis': {'title': "Percentage (%)"}
            }
        },
        {
            'data': [
                Pie(labels=category_names,values=message_cat_perc,hoverinfo='label+percent')
            ],
            'layout': {
                'title': 'Distribution of Message Categories'
            }
        }        
    ]
    
    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)
    
    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #26
0
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    categories = df.drop(['original', 'genre', 'message'], axis=1)
    categories_counts = categories.sum().sort_values(ascending=False)
    categories_names = list(categories_counts.index)

    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [
        {
            'data': [Bar(x=genre_names, y=genre_counts)],
            'layout': {
                'title': 'Distribution of Message Genres',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                }
            }
        },
        {
            'data': [Bar(x=categories_names, y=categories_counts)],
            'layout': {
                'title': 'Bar Diagram of Messeage Categories',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Categories"
                }
            }
        },
        {
            'data': [Pie(labels=categories_names, values=categories_counts)],
            'layout': {
                'title': 'Pie Diagram of Messeage Categories',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Categories"
                }
            }
        },
    ]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #27
0
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    # english - non-english messages percentage
    values = []
    values.append(df['original'].count())
    values.append(df['original'].isnull().sum())
    labels = ['English', 'No English']

    # frequency of words histogram
    df_test = df.drop(columns=['id', 'message', 'original'])
    genre_keys = df_test.aggregate(sum).iloc[1:].reset_index() \
        .sort_values(by=0, ascending=False)['index']
    genre_values = df_test.aggregate(sum).iloc[1:].reset_index() \
        .sort_values(by=0, ascending=False)[0]

    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [
        {
            'data': [Bar(x=genre_names, y=genre_counts)],
            'layout': {
                'title': 'Distribution of Message Genres',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                }
            }
        },
        {
            'data': [Bar(x=genre_keys, y=genre_values)],
            'layout': {
                'title': 'Distribution of Messages',
                'yaxis': {
                    'title': "Count"
                },
            }
        },
        {
            'data': [Pie(labels=labels, values=values)],
            'layout': {
                'title': 'Distribution of Message (English - No english)',
            }
        },
    ]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #28
0
def index():

    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    values_per = df['genre'].value_counts(
        normalize=True).round(3).multiply(100).tolist()
    labels_per_name = df['genre'].value_counts().index.tolist()

    color = np.array(['rgb(55, 83, 109)'] * df.iloc[:, 4:].shape[0])
    color2 = np.array(['rgb(255, 40, 109)'] * df.iloc[:, 4:].shape[0])
    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [{
        'data': [Bar(x=genre_names, y=genre_counts)],
        'layout': {
            'title': 'Distribution of Message Genres',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Genre"
            }
        }
    }, {
        'data': [
            Bar(x=list(df.iloc[:, 4:].columns),
                y=df.iloc[:, 4:].sum(),
                marker=dict(color=color.tolist()))
        ],
        'layout': {
            'title': 'Distribution of Message by Reponse/Outcome',
            'yaxis': {
                'title': "Count"
            },
            'xaxis': {
                'title': "Reponse/Output Variables"
            }
        }
    }, {
        'data': [
            Pie(labels=labels_per_name,
                values=values_per,
                textinfo='label+percent')
        ],
        'layout': {
            'title': 'Percentage Distribution of Message Genres',
        }
    }]

    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #29
0
def index():
    
    # extract data needed for visuals
    # TODO: Below is an example - modify to extract data for your own visuals
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)
    
    Counts_List=genre_counts.values.tolist()
    
    # create visuals
    # TODO: Below is an example - modify to create your own visuals
    graphs = [
        {
            'data': [
                Bar(
                    x=genre_names,
                    y=genre_counts
                )
            ],

            'layout': {
                'title': 'Distribution of Message Genres',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                }
            }
        },
        
        {
            'data': [
                Pie(
                    labels=genre_names,
                    values=Counts_List
                )
            ],

            'layout': {
                'title': 'Distribution of Message Genres',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                }
            }
        }
        
    ]
    
    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)
    
    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)
Пример #30
0
def index():
    
    # extract data needed for visuals
    category_names = df.iloc[:,4:].columns
    category_counts = (df.iloc[:,4:] != 0).sum().values

    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)
    
    # create visuals
    graphs = [
        {

            'data': [
                Bar(
                    x=category_names,
                    y=category_counts
                )
            ],

            'layout': {
                'title': 'Category Distribution',
                'yaxis': {
                    'title': "Numbers"
                },
                'xaxis': {
                    'title': "Category",
                    'tickangle': 30
                }
            }
        },
           { 'data': [
                Pie(
                    labels=genre_names,
                    values=genre_counts
                )
            ],

            'layout': {
                'title': 'Genre Distribution',
                'yaxis': {
                    'title': "Count"
                },
                'xaxis': {
                    'title': "Genre"
                }
            }
        }
           
    ]
    
    # encode plotly graphs in JSON
    ids = ["graph-{}".format(i) for i, _ in enumerate(graphs)]
    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)
    
    # render web page with plotly graphs
    return render_template('master.html', ids=ids, graphJSON=graphJSON)