Exemple #1
0
    def test_dict_unflatten(self):
        """Test passing a spec as keywords."""
        st.vega_lite_chart(
            df1,
            x='foo',
            boink_boop=100,
            baz={'boz': 'booz'},
        )

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(c.HasField('data'), True)
        self.assertDictEqual(
            json.loads(c.spec),
            merge_dicts(
                autosize_spec, {
                    'baz': {
                        'boz': 'booz'
                    },
                    'boink': {
                        'boop': 100
                    },
                    'encoding': {
                        'x': 'foo'
                    }
                }))
Exemple #2
0
def scatter_plot(data):
    """Parameters
    --------
    data: updated dataframe 
    Return
    --------
    Return scatter plot
    """
    st.vega_lite_chart(data, {
            'width': 'container',
            'height': 400,
            'mark':'circle',
            'encoding':{
                'x':{
                'field':'DAYS_BIRTH',
                'type': 'quantitative'
                },
                'y':{
                'field':'AMT_CREDIT',
                'type':'quantitative'
                },
                'size':{
                'field':'AMT_INCOME_TOTAL',
                'type':'quantitative'
                },
                'color':{
                'field':'REGION_RATING_CLIENT',
                'type':'nominal'}
                }
            }, use_container_width=True)
    
#------------------------------------------------------------------------------------------------     
Exemple #3
0
def pageOne(sesh, merchant):
    with open(merchant + '/ins_' + merchant + '_top50_3months_rank.dill',
              'rb') as in_strm:
        df_score = dill.load(in_strm)
    d = df_score.reset_index().rename(
        {
            'username': '******',
            'score': 'Score'
        }, axis='columns')
    d.loc[:, 'Score'] = ['%.2f' % i for i in d['Score']]
    d.loc[:, 'Influencer'] = ['@' + i for i in d['Influencer']]
    d.index += 1
    with open(merchant + '/chart_' + merchant + '.json', "rb") as f:
        chart = json.load(f)

    if not sesh.button_sent:
        st.balloons()
    st.header('Here are the top 5 influencers we recommend for you!')
    st.markdown('###')
    st.write(d[:5])
    st.write(
        'Out of *375* active verified influencers with No. of followers 100 - 1k'
    )

    st.markdown('#')
    st.header('Check out the key metrics.')
    st.markdown('###')
    st.vega_lite_chart(chart, width=800, height=400)

    st.markdown('#')
    st.header(
        "Check out what **your influencer's** ***followers*** are talking about recently."
    )
    show_wc(merchant)
Exemple #4
0
def idhXgraph(dfAtual, bairro_info):
    dadosObito = []
    dadosConfirmado = []
    for i in dfAtual.bairroCaso.value_counts().index:
        filtroBairro = dfAtual.bairroCaso == i
        dfTemp = dfAtual[filtroBairro]
        dadosObito.append([bairro_info.loc[i][0], 
                    dfTemp[dfTemp.obitoConfirmado == 'Verdadeiro'].shape[0]])
        dadosConfirmado.append([bairro_info.loc[i][0], 
                    dfTemp[dfTemp.resultadoFinalExame == 'Positivo'].shape[0]])
    
    dfIdhConfirmado = pd.DataFrame(dadosConfirmado, columns=["IDH", "Casos positivos"])

    st.markdown('### IDH X Casos positivos')
    st.vega_lite_chart(dfIdhConfirmado, {
        "height": 300,
        'mark': {'type': 'circle', 'tooltip': True},
        'encoding': {
            'x': {'field': 'IDH', 'type': 'quantitative'},
            'y': {'field': 'Casos positivos', 'type': 'quantitative'}
        },
    }, use_container_width = True)

    dfIdhObito = pd.DataFrame(dadosObito, columns=["IDH", "Obitos"])

    st.markdown('### IDH X Obitos')
    st.vega_lite_chart(dfIdhObito, {
        "height": 300,
        'mark': {'type': 'circle', 'tooltip': True},
        'encoding': {
            'x': {'field': 'IDH', 'type': 'quantitative'},
            'y': {'field': 'Obitos', 'type': 'quantitative'}
        },
    }, use_container_width = True)
Exemple #5
0
    def test_width_inside_spec(self):
        """Test that {width:-1} leaves the width up to Vega-Lite."""
        st.vega_lite_chart(df1, {'mark': 'rect', 'width': 500})

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertDictEqual(
            json.loads(c.spec), {'mark': 'rect', 'width': 500})
Exemple #6
0
    def test_width_zero(self):
        """Test that width=0 autosets to full width."""
        st.vega_lite_chart(df1, {'mark': 'rect'}, width=0)

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertDictEqual(json.loads(c.spec),
                             merge_dicts(autosize_spec, {'mark': 'rect'}))
Exemple #7
0
    def test_autosize_set(self):
        """Test that autosize doesn't get overriden."""
        st.vega_lite_chart(df1, {'mark': 'rect', 'autosize': None}, width=500)

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertDictEqual(
            json.loads(c.spec),
            {'mark': 'rect', 'autosize': None, 'width': 500})
Exemple #8
0
    def test_datasets_in_spec(self):
        """Test passing datasets={foo: df} inside the spec."""
        st.vega_lite_chart({"mark": "rect", "datasets": {"foo": df1}})

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(c.HasField("data"), False)
        self.assertDictEqual(json.loads(c.spec),
                             merge_dicts(autosize_spec, {"mark": "rect"}))
Exemple #9
0
    def test_spec_but_no_data(self):
        """Test that it can be called with only data set to None."""
        st.vega_lite_chart(None, {"mark": "rect"})

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(c.HasField("data"), False)
        self.assertDictEqual(json.loads(c.spec),
                             merge_dicts(autosize_spec, {"mark": "rect"}))
Exemple #10
0
    def test_spec_in_arg1(self):
        """Test that it can be called spec as the 1st arg."""
        st.vega_lite_chart({"mark": "rect"})

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(c.HasField("data"), False)
        self.assertDictEqual(json.loads(c.spec),
                             merge_dicts(autosize_spec, {"mark": "rect"}))
Exemple #11
0
    def test_use_container_width(self):
        """Test that use_container_width=True autosets to full width."""
        st.vega_lite_chart(df1, {"mark": "rect"}, use_container_width=True)

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertDictEqual(json.loads(c.spec),
                             merge_dicts(autosize_spec, {"mark": "rect"}))

        self.assertEqual(c.use_container_width, True)
def main():
    specification_path = (pathlib.Path(__file__).parent / "specifications" /
                          "connections_among_us_airports.json")
    specification = specification_path.read_text()
    specification = specification.replace(
        '"url": "data/',
        '"url": "https://vega.github.io/vega-lite/examples/data/')
    specification = json.loads(specification)
    st.vega_lite_chart(specification)
Exemple #13
0
    def test_width_inside_spec(self):
        """Test the width up to Vega-Lite."""
        st.vega_lite_chart(df1, {"mark": "rect", "width": 200})

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertDictEqual(
            json.loads(c.spec),
            merge_dicts(autosize_spec, {"mark": "rect", "width": 200}),
        )
Exemple #14
0
    def test_data_in_spec(self):
        """Test passing data=df inside the spec."""
        st.vega_lite_chart({
            'mark': 'rect',
            'data': df1,
        })

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(c.HasField('data'), True)
        self.assertDictEqual(json.loads(c.spec),
                             merge_dicts(autosize_spec, {'mark': 'rect'}))
Exemple #15
0
    def test_width_positive(self):
        """Test that width > 0 sets the width."""
        st.vega_lite_chart(df1, {'mark': 'rect'}, width=500)

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertDictEqual(
            json.loads(c.spec),
            merge_dicts(autosize_spec, {
                'mark': 'rect',
                'width': 500,
            }))
Exemple #16
0
def vegalite():
    st.vega_lite_chart(
        df,
        {
            "mark": {"type": "circle", "tooltip": True},
            "width": 650,
            "height": 500,
            "encoding": {
                "x": {"field": "duration", "type": "quantitative"},
                "y": {"field": "views", "type": "quantitative"},
                "size": {"field": "languages", "type": "quantitative"},
                "color": {"field": "languages", "type": "quantitative"},
            },
        },
    )
Exemple #17
0
 def test_arrow_vega_lite_chart(self, arrow_vega_lite_chart,
                                legacy_vega_lite_chart):
     streamlit.vega_lite_chart(DATAFRAME,
                               None,
                               True,
                               x="foo",
                               boink_boop=100,
                               baz={"boz": "booz"})
     legacy_vega_lite_chart.assert_not_called()
     arrow_vega_lite_chart.assert_called_once_with(DATAFRAME,
                                                   None,
                                                   True,
                                                   x="foo",
                                                   boink_boop=100,
                                                   baz={"boz": "booz"})
def main():
    data = load_data()

    if st.checkbox('Show Data'):
        data

    size_cols = ['price', 'security_deposit', 'cleaning_fee', 'guests_included', 'extra_people',
                'minimum_nights', 'maximum_nights']
    color_cols = ['review_scores_rating', 'review_scores_accuracy', 'review_scores_cleanliness', 
                 'review_scores_checkin', 'review_scores_communication', 'review_scores_location', 
                 'review_scores_value']
    size = st.sidebar.selectbox("Select Size Metric", size_cols)
    color = st.sidebar.selectbox("Select Color Metric", color_cols)

    neighbourhood = st.sidebar.multiselect("Neighbourhood", data['neighbourhood_cleansed'].unique())

    if neighbourhood:
        data = data[data.neighbourhood_cleansed.isin(neighbourhood)]

    super_host = st.sidebar.multiselect("Is host a superhost", data['host_is_superhost'].unique())
    if super_host:
        data = data[data.host_is_superhost.isin(super_host)]

    st.vega_lite_chart(data,{
        'width':'container',
        'height':400,
        'mark':'circle',
        'encoding':{
            'x':{
                'field':'polarity',
                'type':'quantitative',
                'axis': {'title': 'Polarity'}
            },
            'y':{
                'field':'number_of_reviews',
                'type':'quantitative',
                'axis': {'title': 'Number of Reviews'}
            },
            'size':{
                'field': size,
                'type':'quantitative'
            },
            'color':{
                'field': color,
                'type':'quantitative',}
        }
    }, use_container_width=True)
Exemple #19
0
def vega_scatter(df):
    # df = pd.DataFrame(data = [[1,2,1,'train'],[1,3,2,'train'], [3,4,3,'test']],
    #                 columns=['x', 'y', 'c', 'T'])
    circle_type={
        "mark":"circle",
        'height':400,
        'width':700,
        "encoding":{
            "x":{"field":'x', 'type':'quantitative'},
            'y':{'field':'y', 'type':'quantitative'},
            'color':{'field':"c", "type":"nominal"}
        },
        "selection": {
            "grid": {"type": "interval", "bind": "scales"}
        }         
    }
    st.vega_lite_chart(df, circle_type)
Exemple #20
0
    def test_dict_unflatten(self):
        """Test passing a spec as keywords."""
        st.vega_lite_chart(df1, x="foo", boink_boop=100, baz={"boz": "booz"})

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(c.HasField("data"), True)
        self.assertDictEqual(
            json.loads(c.spec),
            merge_dicts(
                autosize_spec,
                {
                    "baz": {"boz": "booz"},
                    "boink": {"boop": 100},
                    "encoding": {"x": "foo"},
                },
            ),
        )
 def _get_unnamed_data_methods(self):
     """DeltaGenerator methods that do not produce named datasets."""
     return [
         lambda df: st.dataframe(df),
         lambda df: st.table(df),
         lambda df: st.vega_lite_chart(
             df, {"mark": "line", "encoding": {"x": "a", "y": "b"}}
         ),
         # TODO: line_chart, bar_chart, etc.
     ]
Exemple #22
0
    def test_no_args_add_rows(self):
        """Test that you can call add_rows on a vega_lite_chart(None)."""
        x = st.vega_lite_chart({"mark": "rect"})

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(c.HasField("data"), False)

        x.add_rows(df1)

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(len(c.data.data.cols[0].strings.data), 4)
Exemple #23
0
    def test_datasets_correctly_in_spec(self):
        """Test passing datasets={foo: df}, data={name: 'foo'} in the spec."""
        st.vega_lite_chart({
            'mark': 'rect',
            'datasets': {
                'foo': df1,
            },
            'data': {
                'name': 'foo',
            },
        })

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(c.HasField('data'), False)
        self.assertDictEqual(
            json.loads(c.spec),
            merge_dicts(
                autosize_spec,
                {'data': {'name': 'foo'}, 'mark': 'rect'}
            )
        )
 def _get_named_data_methods(self):
     """DeltaGenerator methods that produce named datasets."""
     # These should always name the desired data "mydata1"
     return [
         lambda df: st.vega_lite_chart(
             {
                 "mark": "line",
                 "datasets": {"mydata1": df},
                 "data": {"name": "mydata1"},
                 "encoding": {"x": "a", "y": "b"},
             }
         ),
         # TODO: deck_gl_chart
     ]
Exemple #25
0
    def test_add_rows(self):
        """Test that you can call add_rows on a vega_lite_chart(None)."""
        x = st.vega_lite_chart(df1, {"mark": "rect"})

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(len(c.data.data.cols[0].strings.data), 4)

        x.add_rows(df2)

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(len(c.data.data.cols[0].strings.data), 8)
        self.assertDictEqual(json.loads(c.spec),
                             merge_dicts(autosize_spec, {"mark": "rect"}))

        c = self.get_delta_from_queue().new_element.vega_lite_chart
        self.assertEqual(c.HasField("data"), True)
Exemple #26
0
def plotly_line_vega(df):
    df['num_pages'] = df['num_pages'].sort_values()
    df = df.sample(n=200)
    fig = st.vega_lite_chart(
        df, {
            "width": 600,
            "height": 500,
            'mark': {
                'type': 'circle',
                'tooltip': True
            },
            'encoding': {
                'x': {
                    'field': 'num_pages',
                    'type': 'quantitative'
                },
                'y': {
                    'field': 'num_ratings',
                    'type': 'quantitative'
                },
            },
        })
    return fig
Exemple #27
0
# plt.ylabel('Stock Price in $')
# plt.show()

spec = {
    "mark": "line",
    "encoding": {
        "x": {
            "field": X_test,
            "type": "quantitative"
        },
        "y": {
            "field": y_test,
            "type": "quantitative"
        },
    },
}

st.subheader("View dependence on two variables")
plt_2_variables = st.vega_lite_chart(spec, width=500, height=300)
plt_2_variables.vega_lite_chart(data, spec)

# Calculate and print values of MAE, MSE, RMSE
st.markdown("Метрики")
st.text('Mean Absolute Error: %s' %
        metrics.mean_absolute_error(y_test, y_pred))
st.text('Mean Squared Error: %s' % metrics.mean_squared_error(y_test, y_pred))
st.text('Mean Absolute Percentage Error: %s' %
        np.mean(np.abs((y_test - y_pred) / y_test) * 100))
st.text('Root Mean Squared Error: %s' %
        np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
st.text('R2: %s' % metrics.r2_score(y_test, y_pred))
Exemple #28
0
def main():
    st.markdown(
        '<style>  body {background-color: white; color: black}</style>',
        unsafe_allow_html=True)
    st.markdown('<style> h1 {color: sandybrown; text-align: center }</style>',
                unsafe_allow_html=True)
    #st.sidebar.header("sidebar")
    st.sidebar.title('Select a recommendation method ')
    # add_selectbox = st.sidebar.radio(
    #     "->",
    #     ("FastAI", "xDeepFM")
    #     )

    add_selectbox = st.sidebar.selectbox('', ('', 'FastAI', 'xDeepFM'))
    st.sidebar.text(" \n")
    st.sidebar.text(" \n")
    st.sidebar.markdown('---')
    st.sidebar.text(" \n")
    st.sidebar.text(" \n")

    if add_selectbox == 'FastAI':
        st.title("FastAI")
        st.text(" \n")
        st.text(" \n")
        st.header("*The recommendations for this user are : * :arrow_forward:")
        user_input = st.sidebar.number_input("Please Enter User ID",
                                             min_value=0,
                                             max_value=1000,
                                             value=0,
                                             step=1)
        user_in = str(user_input)
        print(type(user_in))
        if st.sidebar.button('Get Recommeded Products'):
            result = get_dataset(user_in)
            # print(result['predictions ']['productId'])
            pred = result['predictions ']
            out = list(
                zip(pred['productId'].values(), pred['Product Name'].values(),
                    pred['Price'].values(), pred['Prediction'].values(),
                    pred['img'].values()))
            productIds = list(pred['productId'].values())
            productNames = list(pred['Product Name'].values())
            productPrice = list(pred['Price'].values())
            preds = list(pred['Prediction'].values())
            image = list(pred['img'].values())
            print(len(productIds))
            print(len(preds))
            df = pd.DataFrame({
                'ProductID': productIds,
                'ProductName': productNames,
                'Productprice': productPrice,
                'Predictions': preds,
                'image': image
            })
            df = df.sort_values(['Predictions'], ascending=False)
            dfcheck = df.loc[0:4, [
                'ProductID', 'ProductName', 'Productprice', 'Predictions',
                'image'
            ]]  #.assign( Table ='').set_index('Table')
            dfcheck = dfcheck.reset_index(drop=True)
            dfcheck2 = dfcheck.loc[0:4, :]
            dfcheck2.set_index("ProductID", inplace=True)
            st.write(dfcheck2.to_html(
                escape=False, formatters=dict(image=path_to_image_html)),
                     unsafe_allow_html=True)
            #st.write(dfcheck.ProductID)
            #st.write(dfcheck.image

            # colors = ['rgb(255,218,185)', 'rgb(255,228,181)', 'rgb(255,239,213)',
            # 'rgb(250,250,210)', 'rgb(255,250,205)']
            # dfn = pd.DataFrame({'ProductID': productIds, 'ProductName': productNames, 'Productprice':productPrice, 'Predictions': preds, 'image': image})
            # dfn = dfn.sort_values(['Predictions'], ascending=False)
            # dfnn2= dfn.loc[0:4,['ProductID' , 'ProductName','Productprice','Predictions','image']].assign( hack ='').set_index('hack')
            # dfnn2['Color'] = colors
            # dfnn3 = st.write(dfnn2.to_html(escape=False ,formatters=dict(image=path_to_image_html)), unsafe_allow_html=True)
            # print(dfnn3.ProductID)
            # fig = go.Figure(data=[go.Table(header=dict(
            #  values=["<b>Product ID<b>", "<b>Product Name</b>", "<b>Product Price</b>","<b>Predicted Rating</b>","<b>Product Image</b>"],
            #  line_color='white', fill_color='olive',
            #  align='center',font=dict(color='white', size=16),height=50
            #  ),
            # cells=dict(
            #  values=[dfnn3.ProductID, dfnn3.ProductName, dfnn3.Productprice, dfnn3.Predictions, dfnn3.image],
            #  line_color=[dfnn2.Color], fill_color=[dfnn2.Color],
            #  align='center',font=dict(color='saddlebrown', size=20),height=50
            #  ))
            # ],layout=layout)
            # #fig.show()python -m pip install -r .\requirements.txt
            # image = PIL.Image.open('my_table3.png')
            # st.image(image, use_column_width=True)

    if add_selectbox == 'xDeepFM':
        st.title("xDeepFM")
        st.text(" \n")
        st.text(" \n")
        st.header("*The recommendations for this user are : * :arrow_forward:")
        user_input2 = st.sidebar.number_input("Please Enter User ID",
                                              min_value=0,
                                              max_value=1000,
                                              value=0,
                                              step=1)
        user_in2 = str(user_input2)
        if st.sidebar.button('Get Recommeded Products'):
            result2 = get_dataset1(user_in2)
            # print(result['predictions ']['productId'])
            pred = result2['Like Prob']
            out = list(
                zip(pred['productId'].values(), pred['Product Name'].values(),
                    pred['Price'].values(), pred['Like Probability'].values(),
                    pred['img'].values()))
            productIds = list(pred['productId'].values())
            productNames = list(pred['Product Name'].values())
            productPrice = list(pred['Price'].values())
            preds = list(pred['Like Probability'].values())
            image = list(pred['img'].values())
            df = pd.DataFrame({
                'Product ID': productIds,
                'Product Name': productNames,
                'Product price': productPrice,
                'Like Probability': preds,
                'image': image
            })

            dfcheck = df.loc[0:4, [
                'Product ID', 'Product Name', 'Product price',
                'Like Probability', 'image'
            ]]  #.assign( Table ='').set_index('Table')
            dfcheck.set_index("Product ID", inplace=True)
            st.write(dfcheck.to_html(
                escape=False, formatters=dict(image=path_to_image_html)),
                     unsafe_allow_html=True)

            # colors = ['rgb(255,218,185)', 'rgb(255,228,181)', 'rgb(255,239,213)',
            # 'rgb(250,250,210)', 'rgb(255,250,205)']

            # dfn = pd.DataFrame({'ProductID': productIds, 'Predictions': preds})
            # dfnn2= dfn.loc[0:4,['ProductID' , 'Predictions']].assign( hack ='').set_index('hack')
            # dfnn2['Color'] = colors
            # fig = go.Figure(data=[go.Table(header=dict(
            #  values=["<b>Product ID<b>", "<b>Like Probability</b>"],
            #  line_color='white', fill_color='olive',
            #  align='center',font=dict(color='white', size=16),height=50
            #  ),
            # cells=dict(
            #     values=[dfnn2.ProductID, dfnn2.Predictions],
            #  line_color=[dfnn2.Color], fill_color=[dfnn2.Color],
            #  align='center',font=dict(color='saddlebrown', size=20),height=50
            #     ))
            # ],layout=layout)
            # #fig.show()
            # fig.write_image("my_table3.png")
            # image = PIL.Image.open('my_table3.png')
            # st.image(image, caption='Sunrise by the mountains', use_column_width=True)

    menu_list = [
        'Execute JMeter Test Plan', 'Analyze JMeter Test Results', 'Home'
    ]
    # Display options in Sidebar
    st.sidebar.title('Load Testing Using Jmeter')
    menu_sel = st.sidebar.radio('', menu_list, index=2, key=None)

    # Display text in Sidebar
    about.display_sidebar()

    # Selecting About Menu
    if menu_sel == 'Home':
        about.display_about()

    # Selecting Execute Menu
    if menu_sel == 'Execute JMeter Test Plan':
        #jmeter_run = st.radio('Select',('Default','Execute','Analyze'))
        #if jmeter_run == 'Execute':
        st.title('Execute JMeter Test Plan')
        jmeter_execute_load()

    #if jmeter_run == 'Analyze':
    if menu_sel == 'Analyze JMeter Test Results':
        st.title('Analyze JMeter Test Results')

        filename = jmeter_analyze()
        st.write('You selected `%s`' % filename)
        #DATA_URL = ('C:\\Users\\Navee\\OneDrive\\Documents\\Tools\\apache-jmeter-5.2\\bin\\Run2.csv')
        DATA_URL = filename

        st.markdown('')
        # Show Graphs Checkbox
        show_graphs = st.checkbox('Show Graphs')

        # Show Profiling Report
        profile_report = st.button('Generate Profiling Report')

        # Generate Profiling Report

        if profile_report:
            st.write('Generating Report for ', filename)
            pd_profile(filename)

        st.title('Apache JMeter Load Test Results')
        data = pd.read_csv(DATA_URL)

        #Display Start Time
        startTime = data['timeStamp'].iloc[0] / 1000
        startTime = datetime.datetime.fromtimestamp(startTime).strftime(
            '%Y-%m-%d %H:%M:%S')
        st.write('Start Time ', startTime)

        endTime = data['timeStamp'].iloc[-1] / 1000
        endTime = datetime.datetime.fromtimestamp(endTime).strftime(
            '%Y-%m-%d %H:%M:%S')
        st.write('End Time ', endTime)

        FMT = '%Y-%m-%d %H:%M:%S'
        delta = datetime.datetime.strptime(
            endTime, FMT) - datetime.datetime.strptime(startTime, FMT)

        st.write('Total duration of the test (HH:MM:SS) is ', delta)

        st.subheader('Summary Report - Response Time')
        st.write(
            data.groupby('label')['elapsed'].describe(
                percentiles=[0.75, 0.95, 0.99]))

        st.subheader('Error Count')
        errCount = data.groupby(['label',
                                 'responseCode'])['responseCode'].count()
        st.write(errCount)

        if show_graphs:
            chart_data = pd.DataFrame(data,
                                      columns=[
                                          'timeStamp', 'Latency', 'label',
                                          'responseCode', 'elapsed', 'Connect',
                                          'bytes'
                                      ])

            st.subheader("Graph between Timestamp and Latency")

            st.vega_lite_chart(
                chart_data, {
                    "mark": {
                        "type": "bar",
                        "color": "maroon"
                    },
                    "selection": {
                        "grid": {
                            "type": "interval",
                            "bind": "scales"
                        }
                    },
                    'encoding': {
                        "tooltip": [{
                            "field": "timeStamp",
                            "type": "temporal"
                        }, {
                            "field": "label",
                            "type": "nominal"
                        }, {
                            "field": "Latency",
                            "type": "quantitative"
                        }],
                        'x': {
                            'field': 'timeStamp',
                            'type': 'temporal'
                        },
                        'y': {
                            'field': 'Latency',
                            'type': 'quantitative'
                        },
                    },
                })

            st.subheader("Graph between Timestamp and Response Code")
            st.vega_lite_chart(
                chart_data, {
                    "mark": {
                        "type": "bar",
                        "color": "aqua"
                    },
                    "selection": {
                        "grid": {
                            "type": "interval",
                            "bind": "scales"
                        }
                    },
                    'encoding': {
                        "tooltip": [{
                            "field": "timeStamp",
                            "type": "temporal"
                        }, {
                            "field": "label",
                            "type": "nominal"
                        }, {
                            "field": "responseCode",
                            "type": "quantitative"
                        }],
                        'x': {
                            'field': 'timeStamp',
                            'type': 'temporal'
                        },
                        'y': {
                            'field': 'responseCode',
                            'type': 'quantitative'
                        },
                    },
                })

            st.subheader("Graph between Timestamp and Response Time")
            st.vega_lite_chart(
                chart_data, {
                    "mark": {
                        "type": "bar",
                        "color": "orange"
                    },
                    "selection": {
                        "grid": {
                            "type": "interval",
                            "bind": "scales"
                        }
                    },
                    'encoding': {
                        "tooltip": [{
                            "field": "timeStamp",
                            "type": "temporal"
                        }, {
                            "field": "label",
                            "type": "nominal"
                        }, {
                            "field": "elapsed",
                            "type": "quantitative"
                        }],
                        'x': {
                            'field': 'timeStamp',
                            'type': 'temporal'
                        },
                        'y': {
                            'field': 'elapsed',
                            'type': 'quantitative'
                        },
                    },
                })

            st.subheader("Graph between Timestamp and Connect Time")
            st.vega_lite_chart(
                chart_data, {
                    "mark": {
                        "type": "bar",
                        "color": "darkgreen"
                    },
                    "selection": {
                        "grid": {
                            "type": "interval",
                            "bind": "scales"
                        }
                    },
                    'encoding': {
                        "tooltip": [{
                            "field": "timeStamp",
                            "type": "temporal"
                        }, {
                            "field": "label",
                            "type": "nominal"
                        }, {
                            "field": "Connect",
                            "type": "quantitative"
                        }],
                        'x': {
                            'field': 'timeStamp',
                            'type': 'temporal'
                        },
                        'y': {
                            'field': 'Connect',
                            'type': 'quantitative'
                        },
                    },
                })

            st.subheader("Graph between Timestamp and bytes")
            st.vega_lite_chart(
                chart_data, {
                    "mark": {
                        "type": "bar",
                        "color": "darkblue"
                    },
                    "selection": {
                        "grid": {
                            "type": "interval",
                            "bind": "scales"
                        }
                    },
                    'encoding': {
                        "tooltip": [{
                            "field": "timeStamp",
                            "type": "temporal"
                        }, {
                            "field": "label",
                            "type": "nominal"
                        }, {
                            "field": "bytes",
                            "type": "quantitative"
                        }],
                        'x': {
                            'field': 'timeStamp',
                            'type': 'temporal'
                        },
                        'y': {
                            'field': 'bytes',
                            'type': 'quantitative'
                        },
                    },
                })

            st.subheader(
                "Graph between Timestamp and Response Time - Line Chart")
            st.vega_lite_chart(
                chart_data, {
                    "mark": "line",
                    "encoding": {
                        "tooltip": [{
                            "field": "timeStamp",
                            "type": "temporal"
                        }, {
                            "field": "label",
                            "type": "nominal"
                        }, {
                            "field": "elapsed",
                            "type": "quantitative"
                        }],
                        "x": {
                            "field": "timeStamp",
                            "type": "temporal"
                        },
                        "y": {
                            "field": "elapsed",
                            "type": "quantitative"
                        },
                        "color": {
                            "field": "label",
                            "type": "nominal"
                        }
                    },
                })

            st.subheader(
                "Graph between Timestamp and Response Time - Bar Chart")
            st.vega_lite_chart(
                chart_data, {
                    "mark": "bar",
                    "encoding": {
                        "tooltip": [{
                            "field": "timeStamp",
                            "type": "temporal"
                        }, {
                            "field": "label",
                            "type": "nominal"
                        }, {
                            "field": "elapsed",
                            "type": "quantitative"
                        }],
                        "x": {
                            "field": "timeStamp",
                            "type": "temporal"
                        },
                        "y": {
                            "field": "elapsed",
                            "type": "quantitative"
                        },
                        "color": {
                            "field": "label",
                            "type": "nominal"
                        }
                    },
                })

            st.subheader("Histogram")
            st.vega_lite_chart(
                chart_data, {
                    "transform": [{
                        "filter": {
                            "and": [{
                                "field": "timeStamp",
                                "valid": True
                            }, {
                                "field": "elapsed",
                                "valid": True
                            }]
                        }
                    }],
                    "mark":
                    "rect",
                    "width":
                    300,
                    "height":
                    200,
                    "encoding": {
                        "x": {
                            "field": "timeStamp",
                            "type": "temporal"
                        },
                        "y": {
                            "field": "elapsed",
                            "type": "quantitative"
                        },
                        "color": {
                            "aggregate": "count",
                            "type": "quantitative"
                        }
                    },
                    "config": {
                        "view": {
                            "stroke": "transparent"
                        }
                    }
                })

            st.subheader("Histogram")
            st.vega_lite_chart(
                chart_data, {
                    "transform": [{
                        "filter": {
                            "and": [{
                                "field": "timeStamp",
                                "valid": True
                            }, {
                                "field": "Connect",
                                "valid": True
                            }]
                        }
                    }],
                    "mark":
                    "rect",
                    "width":
                    300,
                    "height":
                    200,
                    "encoding": {
                        "x": {
                            "field": "timeStamp",
                            "type": "temporal"
                        },
                        "y": {
                            "field": "Connect",
                            "type": "quantitative"
                        },
                        "color": {
                            "aggregate": "count",
                            "type": "quantitative"
                        }
                    },
                    "config": {
                        "view": {
                            "stroke": "transparent"
                        }
                    }
                })

            st.subheader("Scatter Plot between Timestamp and Response Time")
            st.vega_lite_chart(
                chart_data, {
                    "selection": {
                        "grid": {
                            "type": "interval",
                            "bind": "scales"
                        }
                    },
                    "mark": "circle",
                    "encoding": {
                        "tooltip": [{
                            "field": "timeStamp",
                            "type": "temporal"
                        }, {
                            "field": "label",
                            "type": "nominal"
                        }, {
                            "field": "elapsed",
                            "type": "quantitative"
                        }],
                        "x": {
                            "field": "timeStamp",
                            "type": "temporal"
                        },
                        "y": {
                            "field": "elapsed",
                            "type": "quantitative"
                        },
                        "size": {
                            "field": "label",
                            "type": "nominal"
                        }
                    },
                })
Exemple #29
0
import matplotlib.pyplot as plt
import streamlit as st
import pandas as pd

data = pd.DataFrame({"a": [1, 2, 3, 4], "b": [1, 3, 2, 4]})

spec = {
    "mark": "line",
    "encoding": {
        "x": {"field": "a", "type": "quantitative"},
        "y": {"field": "b", "type": "quantitative"},
    },
}

# 5 empty charts
st.vega_lite_chart(spec, use_container_width=True)
fig, ax = plt.subplots()
st.pyplot(fig, use_container_width=True)
st.line_chart()
st.bar_chart()
st.area_chart()

# 1 empty map
# comment this one out to avoid this Cypress-Mapbox related error.
# ref: https://github.com/cypress-io/cypress/issues/4322
# st.pydeck_chart()
# st.map()

# 6 errors
try:
    st.vega_lite_chart({}, use_container_width=True)
Exemple #30
0
        "color": {"field": "c", "type": "quantitative"},
    },
}

spec_with_width = {
    "mark": "circle",
    "encoding": {
        "x": {"field": "a", "type": "quantitative"},
        "y": {"field": "b", "type": "quantitative"},
        "size": {"field": "c", "type": "quantitative"},
        "color": {"field": "c", "type": "quantitative"},
    },
    "width": "500",
}

st.vega_lite_chart(df, spec, use_container_width=True)
st.vega_lite_chart(df, spec, use_container_width=True)
st.vega_lite_chart(df, spec)
st.vega_lite_chart(df, spec_with_width)

# Screenshot comparison

st.header("Different ways to get the exact same plot")

df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T

st.write("Using a top-level `df` and a `spec` dict:")

st.vega_lite_chart(
    df,
    {