Python/Dash by Plotly:按d分组案例

2024-10-04 03:27:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我只能绘制总发生案例的条形图,而不是按发生日期分组,代码如下:

 trace1=go.Bar(
    x=pd.to_datetime(dfb['date']),
    y=dfb.set_index('date').resample('M')["enrolled"].sum(),
    )

如何按日期分组? 数据集如下

^{pr2}$

谢谢


Tags: to代码godatetimedateindex绘制bar
3条回答

我在我的data.csv中使用了以下内容:

date   enrolled
6/29/2018   1
6/29/2018   1
6/29/2018   0
6/29/2018   1
6/20/2018   1
6/22/2018   1
6/19/2018   1
6/27/2018   1
6/28/2018   0
6/27/2018   1
6/19/2018   1
6/20/2018   1
6/27/2018   1
6/27/2018   0
6/26/2018   1
6/27/2018   0
6/27/2018   1

这是解决plotly问题的一个可能的解决方案:

^{pr2}$

此示例使用破折号发布图形:

import pandas as pd

# Read in data (might be already given in your code)
df = pd.read_csv('data.csv', delimiter='   ')
groups = df.groupby(['date'])

xData = []
yData = []

# Group data by keys and get sum
for group, data in df.groupby(['date']):
    xData.append(group)
    yData.append(data['enrolled'].sum())

# Dash specific stuff
import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()

app.layout = html.Div(children=[
    html.H1(
        children='Hello Dash',
    ),

    html.Div(children='Dash: A web application framework for Python.', style={
        'textAlign': 'center'
    }),

    dcc.Graph(
        id='example-graph-2',
        figure={
            'data': [
                {'x':xData, 'y': yData, 'type': 'bar'},
            ],
            'layout': {}
            }

    )
])

if __name__ == '__main__':
    app.run_server(debug=True)
Save this data as final_test.csv to have same results as mine. Thanks

date    enrolled
6/29/2018   1
6/29/2018   1
6/29/2018   
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/20/2018   1
6/20/2018   1
6/22/2018   1
6/19/2018   1
6/19/2018   1
6/27/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   
6/28/2018   1
6/28/2018   1
6/20/2018   1
6/20/2018   1
6/19/2018   1
6/19/2018   1
6/26/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/19/2018   1
6/19/2018   1
6/19/2018   1
6/22/2018   1
6/20/2018   1
6/20/2018   1
6/20/2018   1
6/20/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/19/2018   1
6/19/2018   1
6/19/2018   1
6/19/2018   1
6/19/2018   1
6/20/2018   1
6/20/2018   1
6/20/2018   1
6/20/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/20/2018   1
6/20/2018   1
6/20/2018   1
6/20/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/19/2018   1
6/26/2018   1
6/26/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   
6/26/2018   1
6/27/2018   
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/29/2018   1
6/26/2018   
6/27/2018   1
6/28/2018   
6/28/2018   1
6/19/2018   1
6/19/2018   1
6/19/2018   1
6/20/2018   1
6/20/2018   1
6/20/2018   1
6/20/2018   1
6/20/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/20/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/20/2018   1
6/21/2018   1
6/21/2018   1
6/21/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/26/2018   1
6/26/2018   1
6/22/2018   1
6/22/2018   1
6/22/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/27/2018   1
6/27/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/19/2018   1
6/19/2018   1
6/19/2018   1
6/20/2018   1
6/20/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/27/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/26/2018   1
6/27/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/27/2018   1
6/27/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/28/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
6/29/2018   1
#### Importing DASH COMPONENTS ##############################################################################
#coding: utf-8

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html

from plotly import graph_objs as go # or
#import plotly.graph_objs as go
import ipywidgets as widgets
from scipy import special

import datetime #To allow displaying today's Date in upper right corner

import json
import pandas as pd
import os
from flask import Flask
import numpy as np



#### Preparing FLASK App ####################################################################################
server = Flask('my app')

#### SCATTER PLOT  ########################################################################################## 

dfb=pd.read_csv('final_test.csv', encoding="latin-1", infer_datetime_format=True, parse_dates=['date'], skipinitialspace=True)

trace1=go.Bar(                              #Trace Enrollment

    x=pd.to_datetime(dfb['date']), 
    y=dfb.set_index('date').resample('M')["enrolled"].sum(),
    #y=dfb.groupby('date').enrolled.sum(),  
    #mode='lines + markers',
    name='Enrollment',
)

trace2=go.Bar(                              #Trace empty enrollment
    x=pd.to_datetime(dfb['date']),
    y=dfb[dfb['enrolled'].isnull()].sum(), 
    name='Not Answered',
    #xaxis='Performance'
)

trace3=go.Bar(                              #Trace Rejection to Enrollment
    x=pd.to_datetime(dfb['date']),
    y=dfb[dfb['enrolled'] == 2].sum(),
    name='Rejected Participation',
    #xaxis='Performance'
)

#### PERFORMANCE % ##########################################################################################



#############################################################################################################
#### CREATE STANDARD TABLES OF OUTPUT #########################################################################
def make_dash_table(df):
    ''' Return a dash definitio of an HTML table for a Pandas dataframe '''
    table = []
    for index, row in df.iterrows():
        html_row = []
        for i in range(len(row)):
            html_row.append(html.Td([row[i]]))
        table.append(html.Tr(html_row))
    return table

#############################################################################################################

app = dash.Dash()

# Describe the layout, or the UI, of the app
app.layout = html.Div([

    html.Div([  # page 1

        html.A(['Print PDF'],
               className="button no-print",
               style={'position': "absolute", 'top': '-40', 'right': '0'}),

        html.Div([  # subpage 1

            # Row 1 (Header)

            html.Div([

                html.Div([
                    html.H5(
                        'An Example of DashBoard in Dash from Plotly'),
                    html.H6('Summary',
                            style={'color': '#7F90AC'}),
                ], className="nine columns padded"),

                html.Div([
                    html.H1(
                        #[html.Span('03', style={'opacity': '0.5'}), html.Span('17')]),
                        datetime.datetime.now().strftime('%Y-%m-%d'), style={'opacity': '1','color': 'white', 'fontSize': 12}),
                    html.H1(datetime.datetime.now().strftime('%H:%M:%S'), style={'font-family': 'Times New Roman','opacity': '0.5','color': 'white', 'fontSize': 12}),
                    html.H6('Daily Updates')
                ], className="three columns gs-header gs-accent-header padded", style={'float': 'right'}),

            ], className="row gs-header gs-text-header"),

            html.Br([]),

            # Row 2

            html.Div([

                html.Div([
                    html.H6('Resume',
                            className="gs-header gs-text-header padded"),



                ], className="four columns"),



                html.Div([

               html.Div(children=[

    html.H6(["Performance"],
                            className="gs-header gs-table-header padded"),                  
        dcc.Graph(
            id='example-graph',
            figure={
                'data': [trace1, trace2, trace3],
                'layout':
                go.Layout(
                title='', width="508", height="300", legend=dict(x=0, y=7),
                margin={'l': 20, 'b': 40, 't': 10, 'r': 65},

                font=dict(
            family='sans-serif',
            size=8,
            color='#000'
        ), 

        plot_bgcolor='#D9E0EC',



                xaxis=dict(


        title='',
        tickangle=45,
        ticklen=5,
        #zeroline=False,
        gridwidth=2,
        showticklabels=True,
        nticks=6,
    ),
    yaxis=dict(
        title='',
        ticklen=5,
        gridwidth=4,
    ),

                )#, barmode='stack')
        })
]),


     ], className="eight columns"),
 ], className="row "),



        ], className="subpage"),

    ], className="page"),



])

if 'DYNO' in os.environ:
    app.scripts.append_script({
        'external_url': 'https://cdn.rawgit.com/chriddyp/ca0d8f02a1659981a0ea7f013a378bbd/raw/e79f3f789517deec58f41251f7dbb6bee72c44ab/plotly_ga.js'
    })

external_css = ["https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css",
                "https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css",
                "//fonts.googleapis.com/css?family=Raleway:400,300,600",
                "https://cdn.rawgit.com/plotly/dash-app-stylesheets/5047eb29e4afe01b45b27b1d2f7deda2a942311a/goldman-sachs-report.css",
                "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"]

for css in external_css:
    app.css.append_css({"external_url": css})

external_js = ["https://code.jquery.com/jquery-3.2.1.min.js",
               "https://cdn.rawgit.com/plotly/dash-app-stylesheets/a3401de132a6d0b652ba11548736b1d1e80aa10d/dash-goldman-sachs-report-js.js"]

for js in external_js:
    app.scripts.append_script({"external_url": js})


if __name__ == '__main__':
    app.server.run()

相关问题 更多 >