Esempio n. 1
1
def show(sample_size):
    global session
    global scatter_plot
    global source
    global pie_chart_source
    global line_chart_source
    global slider
    DB.__init__(sample_size)
    min_time = DB.min_time()
    max_time = DB.max_time()
    print min_time
    print min_time
    xs, ys, color, time = DB.get_current()
    xs = [xs[i] for i,v in enumerate(time) if time[i] == min_time]
    ys = [ys[i] for i,v in enumerate(time) if time[i] == min_time]
    color = [color[i] for i,v in enumerate(time) if time[i] == min_time]

    time_dict = Counter(time)
    pie_chart_source = ColumnDataSource(data=ChartMath.compute_color_distribution('x', 'y', 'color', color))
    line_chart_source = ColumnDataSource(data=dict(x=[key for key in time_dict], y=[time_dict[key] for key in time_dict]))
    source = ColumnDataSource(data=dict(x=xs, y=ys, color=color))

    scatter_plot = Figure(plot_height=800,
                          plot_width=1200,
                          title="Plot of Voters",
                          tools="pan, reset, resize, save, wheel_zoom",
                          )

    scatter_plot.circle('x', 'y', color='color', source=source, line_width=0, line_alpha=0.001, fill_alpha=0.5, size=15)
    scatter_plot.patches('x', 'y', source=state_source, fill_alpha=0.1, line_width=3, line_alpha=1)

    scatter_plot.x_range.on_change('end', update_coordinates)
    line_chart = Figure(title="Distribution over Time", plot_width=350, plot_height=350)
    line_chart.line(x='x', y='y', source=line_chart_source)
    pie_chart_plot = Figure(plot_height=350,
                            plot_width=350,
                            title="Voter Distribution",
                            x_range=(-1, 1),
                            y_range=(-1, 1))
    pie_chart_plot.wedge(x=0, y=0, source=pie_chart_source, radius=1, start_angle="x", end_angle="y", color="color")
    slider = Slider(start=min_time, end=max_time, value=min_time, step=1, title="Time")

    slider.on_change('value', update_coordinates)
    h = hplot(scatter_plot, vplot(pie_chart_plot, line_chart))
    vplot(slider, h, width=1600, height=1800)
    session = push_session(curdoc())
    session.show()
    #script = autoload_server(scatter_plot, session_id=session.id)
    session.loop_until_closed()
Esempio n. 2
0
def pie_viz(
    df: pd.DataFrame,
    col: str,
    miss_pct: float,
    plot_width: int,
    plot_height: int,
) -> Panel:
    """
    Render a pie chart
    """
    title = f"{col} ({miss_pct}% missing)" if miss_pct > 0 else f"{col}"
    tooltips = [(f"{col}", "@col"), ("Count", "@cnt"),
                ("Percent", "@pct{0.2f}%")]
    df["angle"] = df["cnt"] / df["cnt"].sum() * 2 * pi
    fig = Figure(
        title=title,
        plot_width=plot_width,
        plot_height=plot_height,
        tools="hover",
        toolbar_location=None,
        tooltips=tooltips,
    )
    color_list = PALETTE * (len(df) // len(PALETTE) + 1)
    df["colour"] = color_list[0:len(df)]
    if df.iloc[-1]["cnt"] == 0:  # no "Others" group
        df = df[:-1]
    pie = fig.wedge(
        x=0,
        y=1,
        radius=0.9,
        start_angle=cumsum("angle", include_zero=True),
        end_angle=cumsum("angle"),
        line_color="white",
        fill_color="colour",
        source=df,
    )
    legend = Legend(
        items=[LegendItem(label=dict(field="col"), renderers=[pie])])
    legend.label_text_font_size = "8pt"
    fig.add_layout(legend, "right")
    tweak_figure(fig, "pie")
    fig.axis.major_label_text_font_size = "0pt"
    fig.axis.major_tick_line_color = None
    return Panel(child=fig, title="pie chart")
Esempio n. 3
0
def custom_reports(report_id):

    if report_id == 'A':

        # result = db_session.execute('''select ga_date,sum(page_views),floor(dbms_random.value(2000, 6000)) as sales
        #                                from ga_sink
        #                                group by ga_date''' ).fetchall()

        result = db_session.execute(
            '''select T1.ga_date,T1.page_views, T2.total_sale
                                       from (select ga_date,sum(page_views) as page_views from ga_sink group by ga_date) T1
                                       join (select sale_date,sum(amount) as total_sale from demo_sales group by sale_date) T2
                                       on T1.ga_date=T2.sale_date''').fetchall(
            )

        # result = db_session.execute('''select T1."date",T1.page_views, T2.total_sale
        #                                from (select "date",sum(page_views) as page_views from test group by "date") T1
        #                                join (select sale_date,sum(amount) as total_sale from demo_sales group by sale_date) T2
        #                                on T1."date"=T2.sale_date''' ).fetchall()
        print(result)

        test = pd.DataFrame(result,
                            columns=['date', 'page_views', 'total_sale'])
        test['date'] = pd.to_datetime(test['date'])
        test.set_index(keys=['date'], inplace=True)
        test.sort_index(inplace=True)

        cds = ColumnDataSource(test)

        p = Figure(plot_width=1000,
                   plot_height=500,
                   title="Sales Vs Views",
                   y_range=Range1d(start=2500, end=33000),
                   x_axis_type='datetime',
                   x_axis_label='Date',
                   y_axis_label='Revenue($)')
        l1 = p.line('date',
                    'page_views',
                    source=cds,
                    line_color=d3['Category10'][10][0],
                    line_width=5,
                    legend="Page Views")
        l2 = p.line('date',
                    'total_sale',
                    source=cds,
                    line_color=d3['Category10'][10][1],
                    line_width=5,
                    legend="Revenue")
        p.extra_y_ranges = {"foo": Range1d(start=0, end=6000)}
        p.add_layout(
            LinearAxis(y_range_name='foo', axis_label="Number of Views"),
            'right')
        p.legend.location = "bottom_right"
        p.background_fill_color = "beige"
        p.background_fill_alpha = 0.5
        p.border_fill_color = "#F8F8FF"

        p.add_tools(
            HoverTool(
                renderers=[l1],
                tooltips=[
                    ('date',
                     '@date{%F}'),  # use @{ } for field names with spaces
                    ('views', '@page_views'),
                ],
                formatters={
                    'date':
                    'datetime',  # use 'datetime' formatter for 'date' field
                    # use default 'numeral' formatter for other fields
                },

                # display a tooltip whenever the cursor is vertically in line with a glyph
                mode='vline'))

        p.add_tools(
            HoverTool(
                renderers=[l2],
                tooltips=[
                    # ( 'date',   '@date{%F}'            ),
                    ('revenue', '$@{total_sale}'
                     ),  # use @{ } for field names with spaces
                ],
                formatters={
                    # 'date'      : 'datetime', # use 'datetime' formatter for 'date' field
                    'revenue':
                    'printf',  # use 'printf' formatter for 'adj close' field
                    # use default 'numeral' formatter for other fields
                },

                # display a tooltip whenever the cursor is vertically in line with a glyph
                mode='vline'))

        return json.dumps(json_item(p))

    if report_id == "B":
        result = db_session.execute(
            '''select product_id,sum(page_views) as views
                                       from ga_sink
                                       group by product_id
                                       order by views desc ''').fetchall()

        # result = db_session.execute('''select product_id,sum(page_views) as views
        #                                from test
        #                                group by product_id
        #                                order by views desc ''' ).fetchall()

        test = pd.DataFrame(result, columns=['product_id', 'page_views'])
        test.set_index(keys=['product_id'], inplace=True)

        cds = ColumnDataSource(test)

        p = Figure(x_range=cds.data['product_id'],
                   plot_height=350,
                   title="Top Products by Views",
                   tools="")

        p.vbar(x='product_id',
               top='page_views',
               source=cds,
               width=0.9,
               fill_color=factor_cmap(field_name='product_id',
                                      palette=d3['Category10'][10],
                                      factors=cds.data['product_id']))
        p.xgrid.grid_line_color = None
        p.y_range.start = 0
        p.background_fill_color = "beige"
        p.background_fill_alpha = 0.5
        p.border_fill_color = "#F8F8FF"

        return json.dumps(json_item(p))
    if report_id == "C":
        # cdata= [{'product_id':'BGB-US-001','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-002','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-003','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-004','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-005','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-006','total_sale': random.randint(1000,8000)},
        #             {'product_id':'BGB-US-007','total_sale': random.randint(1000,8000)}]

        cdata = db_session.execute('''select product_id,sum(amount)
                                     from demo_sales
                                     group by product_id''').fetchall()
        c = pd.DataFrame(cdata, columns=['product_id', 'amount'])
        c.rename(columns={"amount": "total_sale"}, inplace=True)
        print(c)
        c.set_index(keys=['product_id'], inplace=True)
        c['angle'] = c['total_sale'] / c['total_sale'].sum() * 2 * pi
        c['color'] = d3['Category10'][10][len(c) - 1::-1]
        c['percent'] = round(c['total_sale'] / c['total_sale'].sum() * 100, 0)

        cds = ColumnDataSource(c)

        p = Figure(plot_height=350,
                   title="Revenue Breakdown by Product",
                   tools="hover",
                   tooltips="@product_id: @percent %",
                   x_range=(-0.5, 1.0))

        p.wedge(x=0,
                y=1,
                radius=0.4,
                start_angle=cumsum('angle', include_zero=True),
                end_angle=cumsum('angle'),
                line_color="white",
                fill_color='color',
                legend='product_id',
                source=cds)

        p.axis.axis_label = None
        p.axis.visible = False
        p.grid.grid_line_color = None
        p.background_fill_color = "beige"
        p.background_fill_alpha = 0.5
        p.border_fill_color = "#F8F8FF"

        return json.dumps(json_item(p))