Exemplo n.º 1
0
def select_slider():
    st.write("""
        # Introducing st.select_slider

        With `st.select_slider`, you can now display a slider using values from a list or object.
        This functions similarly to **[st.slider](https://docs.streamlit.io/en/stable/api.html#streamlit.slider)**
        but for discrete and/or non-numerical data. Please note that values are not sorted and will be listed in the order they are provided.

        For more details, please see our [documentation](https://docs.streamlit.io/en/stable/api.html#streamlit.select_slider)
        """)

    with st.echo("below"):
        st.write("### Example 1: ###")
        w1 = st.select_slider("Label 1",
                              options=[
                                  'red', 'orange', 'yellow', 'green', 'blue',
                                  'indigo', 'violet'
                              ])
        st.write("Selected value:", w1)

    with st.echo("below"):
        st.write("### Example 2:###")
        w2 = st.select_slider("Label 1",
                              options=[10, 40, 50, 90, 121, 800, 1000],
                              value=(40, 121))
        st.write("Selected value:", w2)
Exemplo n.º 2
0
    def test_outside_form(self):
        """Test that form id is marshalled correctly outside of a form."""

        st.select_slider("foo", ["bar", "baz"])

        proto = self.get_delta_from_queue().new_element.slider
        self.assertEqual(proto.form_id, "")
def __populate_clustering_category_sliders(weight_map):
    default_values = dict()
    default_options = list(weight_map.keys())
    default_option = default_options[
        int((len(default_options) - 1) / 2)
    ]
    index = 0
    category_relevance_columns = st.beta_columns(len(GLOBAL_FIELDS.keys()))
    for category, features in GLOBAL_FIELDS.items():
        with category_relevance_columns[index]:
            st.subheader(category)
            weight = st.select_slider(
                "",
                options=default_options,
                value=default_option,
                key=index
            )
            with st.beta_expander(label='', expanded=False):
                for feature in features:
                    default_values[feature] = st.select_slider(
                        feature,
                        options=default_options,
                        value=weight)
        index += 1

    return default_values
Exemplo n.º 4
0
    def test_pandas_series_with_range(self):
        """Test that it can be called with options=pandas series, value=range"""
        st.select_slider(
            "the label", value=(2, 5), options=pd.Series([1, 2, 3, 4, 5, 6])
        )

        c = self.get_delta_from_queue().new_element.slider
        self.assertEqual(c.default, [1, 4])
Exemplo n.º 5
0
    def test_range_out_of_order(self):
        """Test a range that is out of order."""
        st.select_slider(
            "the label", value=("yellow", "red"), options=["red", "orange", "yellow"]
        )

        c = self.get_delta_from_queue().new_element.slider
        self.assertEqual(c.default, [0, 2])
Exemplo n.º 6
0
    def test_just_disabled(self):
        """Test that it can be called with disabled param."""
        st.select_slider(
            "the label", options=["red", "orange", "yellow"], disabled=True
        )

        c = self.get_delta_from_queue().new_element.slider
        self.assertEqual(c.disabled, True)
Exemplo n.º 7
0
    def test_options_types(self, value, options, default):
        """Test that it supports different types of options."""

        st.select_slider("the label", value=value, options=options)

        c = self.get_delta_from_queue().new_element.slider
        self.assertEqual(c.label, "the label")
        self.assertEqual(c.default, default)
Exemplo n.º 8
0
    def test_range(self):
        """Test that a range is specified correctly."""
        st.select_slider(
            "the label", value=("red", "yellow"), options=["red", "orange", "yellow"]
        )

        c = self.get_delta_from_queue().new_element.slider
        self.assertEqual(c.default, [0, 2])
Exemplo n.º 9
0
    def test_numpy_array_with_range(self):
        """Test that it can be called with options=numpy array, value=range"""
        st.select_slider(
            "the label", value=(2, 5), options=np.array([1, 2, 3, 4, 5, 6])
        )

        c = self.get_delta_from_queue().new_element.slider
        self.assertEqual(c.default, [1, 4])
Exemplo n.º 10
0
    def test_no_value(self):
        """Test that it can be called with no value."""
        st.select_slider("the label", options=["red", "orange", "yellow"])

        c = self.get_delta_from_queue().new_element.slider
        self.assertEqual(c.label, "the label")
        self.assertEqual(c.default, [0])
        self.assertEqual(c.min, 0)
        self.assertEqual(c.max, 2)
        self.assertEqual(c.step, 1)
Exemplo n.º 11
0
    def test_inside_form(self):
        """Test that form id is marshalled correctly inside of a form."""

        with st.form("form"):
            st.select_slider("foo", ["bar", "baz"])

        # 2 elements will be created: form block, widget
        self.assertEqual(len(self.get_all_deltas_from_queue()), 2)

        form_proto = self.get_delta_from_queue(0).add_block
        select_slider_proto = self.get_delta_from_queue(1).new_element.slider
        self.assertEqual(select_slider_proto.form_id, form_proto.form.form_id)
Exemplo n.º 12
0
    def test_select_slider_serde(self):
        select_slider = st.select_slider("select_slider",
                                         options=["a", "b", "c"],
                                         key="select_slider")
        check_roundtrip("select_slider", select_slider)

        select_slider_range = st.select_slider(
            "select_slider_range",
            options=["a", "b", "c"],
            value=["a", "b"],
            key="select_slider_range",
        )
        check_roundtrip("select_slider_range", select_slider_range)
Exemplo n.º 13
0
def main():
    data = pd.read_csv("research-and-development-survey-2019-csv.csv")
    data_1 = pd.read_csv(
        "greenhouse-gas-emissions-by-region-industry-and-household-year-ended-2018-csv.csv"
    )
    st.dataframe(data)
    st.table(data.iloc[0:10])

    st.dataframe(data_1)
    st.table(data_1.iloc[0:10])
    st.line_chart(data_1)

    st.json({'foo': 'bar', 'fu': 'ba'})
    st.beta_container()
    st.beta_columns(4)
    col1, col2 = st.beta_columns(2)
    col1.subheader('Columnisation')
    st.beta_expander('Expander')
    with st.beta_expander('Expand'):
        st.write('Juicy deets')

    st.sidebar.write("# Noniot")
    a = st.sidebar.radio('R:', [1, 2])
    st.button('Hit me')
    st.checkbox('Check me out')
    st.radio('Radio', [1, 2, 3])
    st.selectbox('Select', [1, 2, 3])
    st.multiselect('Multiselect', [1, 2, 3])
    st.slider('Slide me', min_value=0, max_value=10)
    st.select_slider('Slide to select', options=[1, '2'])
    st.text_input('Enter some text')
    st.number_input('Enter a number')
    st.text_area('Area for textual entry')
    st.date_input('Date input')
    st.time_input('Time entry')
    st.file_uploader('File uploader')
    st.color_picker('Pick a color')

    st.progress(90)
    st.spinner()
    with st.spinner(text='In progress'):
        time.sleep(5)
        st.success('Done')
    st.balloons()
    st.error('Error message')
    st.warning('Warning message')
    st.info('Info message')
    st.success('Success message')
    st.exception("e")
Exemplo n.º 14
0
def continuous_ttest_from_stats_ui():
    '''The Two-sample Student's t-test - Continuous variables (from statistics) section. '''
    
    # Render the header. 
    with st.beta_container():
        st.title('Two-sample Student\'s t-test')
        st.header('Continuous variables')

    # Render input boxes and plots
    with st.beta_container():
        col1, col2 = st.beta_columns([1, 1])
        with col1:  
            st.subheader('Group A')
            visitors_1 = st.number_input('Sample size A: ', value=80000)
            mu_1 = st.number_input('Sample mean A: ', value=64.5)
            sigma_1 = st.number_input('Sample standard deviation A: ', min_value=0.0, value=30.8)
            conf_level = st.select_slider('Confidence level: ', ('0.90', '0.95', '0.99'))
        with col2: 
            st.subheader('Group B')
            visitors_2 = st.number_input('Sample size B: ', value=80000)
            mu_2 = st.number_input('Sample mean B: ', value=68.7)
            sigma_2 = st.number_input('Sample standard deviation B: ', min_value=0.0, value=38.1)
            hypo_type = st.radio('Hypothesis type: ', ('One-sided', 'Two-sided'))     

    # Calculate statistics
    tstat, p_value, tstat_denom, pooled_sd, effect_size = scipy_ttest_ind_from_stats(
        mu_1, mu_2, sigma_1, sigma_2, visitors_1, visitors_2)
    observed_power = sm_tt_ind_solve_power(effect_size=effect_size, n1=visitors_1, n2=visitors_2, alpha=1-float(conf_level), power=None, hypo_type=hypo_type, if_plot=False)

    # Render the results
    ttest_plot(mu_1, mu_2, sigma_1, sigma_2, conf_level, tstat, p_value, tstat_denom, hypo_type, observed_power)
Exemplo n.º 15
0
def vio_year():
    rl_vio1 = doc(1).dropna(subset=["MONTH"])
    rl_vio2 = doc(2).dropna(subset=["MONTH"])
    rl_vio1["DATE"] = pd.to_datetime(rl_vio1["YEAR"].astype("str").str.cat(rl_vio1["MONTH"].astype("str")),format="%Y%m")
    rl_vio2["DATE"] = pd.to_datetime(rl_vio2["YEAR"].astype("str").str.cat(rl_vio2["MONTH"].astype("str")),format="%Y%m")

    vio3 =pd.DataFrame(rl_vio1).merge(pd.DataFrame(rl_vio2), on = "DATE").rename(
    columns={"VIOLATIONS_x": "Red Light", "VIOLATIONS_y": "Speed"})
    st.area_chart(vio3.set_index("DATE")[["Red Light", "Speed"]], width =850) 
    st.text("Slide the slider to view the number of violations in Chicago.")
    year = st.select_slider("Year", options=[2015, 2016, 2017, 2018, 2019, 2020, 2021], value=2018)
    vio1 = rl_vio1[rl_vio1["YEAR"] == year].groupby("MONTH")["VIOLATIONS"].sum()
    vio2 = rl_vio2[rl_vio2["YEAR"] == year].groupby("MONTH")["VIOLATIONS"].sum()
    vio = pd.DataFrame(vio1).merge(pd.DataFrame(vio2), left_index=True, right_index=True).rename(
        columns={"VIOLATIONS_x": "Red Light", "VIOLATIONS_y": "Speed"})


    fig = plt.figure(figsize=(7, 4))  # Create matplotlib figure
    ax = fig.add_subplot(111)  # Create matplotlib axes
    ax2 = ax.twinx()  # Create another axes that shares the same x-axis as ax.
    width = 0.8
    vio.plot(kind='bar', ax=ax, width=width, rot=0, color=["#e7ba52", "#1f77b4"])
    ax.set_ylabel('Red Light Violation Cases')
    ax2.set_ylabel('Speed Violation Cases')
    ax.set_xlabel("Month")
    plt.grid(False)
    plt.xticks(rotation=45)
           
    return fig
Exemplo n.º 16
0
def sachbegriff_cloud():
    #wordcloud der top 100 sachbegriffe eines auszuwählenden tages der letzten 10 werktage
    st.header('TOP 100 Sachbegriffe pro Tag')
    st.write(
        'Wählen Sie ein Datum aus den letzten 10 Werktagen vor der letzten Aktualisierung der Daten des Dashboards und sehen Sie eine Wordcloud der 100 meistverwendeten GND-Sachbegriffe dieses Tages. Die Größe des Begriffes entspricht der Häufigkeit des Sachbegriffs.'
    )
    files = glob.glob(f'{path}/../stats/*Ts-count.csv')
    daten = [x[-23:-13] for x in files]
    daten.sort()
    daten_filter = st.select_slider('Wählen Sie ein Datum',
                                    options=daten,
                                    value=daten[-1])

    df = pd.read_csv(f'{path}/../stats/{daten_filter}-Ts-count.csv')

    dict = df.to_dict(orient='records')
    worte = {}
    for record in dict:
        worte.update({record['sachbegriff']: record['count']})

    wc = WordCloud(background_color="white",
                   max_words=100,
                   width=2000,
                   height=800,
                   colormap='tab20')
    wc.generate_from_frequencies(worte)
    return st.image(wc.to_array())
Exemplo n.º 17
0
def analyseRegion():
    st.header("Region wise Sales analysis of Video Games")
    st.subheader('Analysis of different region with respect to publisher')
    n = st.select_slider(options=[i * 5 for i in range(1, 11)],
                         label="Select No. of Games")
    selRegion = st.selectbox(options=[
        'NA_Sales',
        'EU_Sales',
        'JP_Sales',
        'Other_Sales',
        'Global_Sales',
    ],
                             label="Select Region")
    st.subheader(
        'Bar chart of showing sum of revenue earned by games (in Billion $)')
    st.bar_chart(analysis.getRegionAndPlatformSum(selRegion, n))

    st.subheader('Bar chart of showing count of games(in Billion $)')
    st.bar_chart(analysis.getRegionAndPlatformCount(selRegion, n))

    st.header('Analysis of different region with respect to publisher')
    st.subheader(
        'Bar chart of showing sum of revenue earned by games (in Billion $)')
    st.bar_chart(analysis.getRegionAndPublisherSum(selRegion, n))

    st.subheader('Bar chart of showing count of games (in Billion $)')
    st.bar_chart(analysis.getRegionAndPublisherCount(selRegion, n))

    data = analysis.getRegionSum()
    fig = plotpie(data.index, data.values, 'Total Region Sales')
    st.plotly_chart(fig)
Exemplo n.º 18
0
def render_top_k_summary(source_path: str, prefix: str, epoch_index: int):
    """ Show top-k summary plot.

    Args:
        source_path (str): The root path of the dumped snapshots data for the corresponding experiment.
        prefix (str): Prefix of data folders.
        epoch_index (int): The index of selected epoch.
    """
    helper.render_h3_title("Cike Bike Top K")
    data = helper.read_detail_csv(
        os.path.join(
            source_path,
            f"{prefix}{epoch_index}",
            GlobalFileNames.stations_sum
        )
    )
    # Convert index to station name.
    index_name_conversion = helper.read_detail_csv(os.path.join(source_path, GlobalFileNames.name_convert))
    data["station name"] = list(
        map(
            lambda x: index_name_conversion.loc[int(x[9:])][0],
            data["name"]
        )
    )
    # Generate top summary.
    top_number = st.select_slider(
        "Select Top K",
        list(range(1, 6))
    )
    top_attributes = ["bikes", "trip_requirement", "fulfillment", "fulfillment_ratio"]
    for item in top_attributes:
        helper.generate_by_snapshot_top_summary("station name", data, int(top_number), item)
Exemplo n.º 19
0
def _generate_top_k_summary(data: pd.DataFrame, snapshot_index: int, index_name_conversion: pd.DataFrame):
    """Generate CIM top k summary.

    Args:
        data (pd.Dataframe): Data of current snapshot.
        snapshot_index (int): Selected snapshot index.
        index_name_conversion (pd.Dataframe): Relationship between index and name.
    """
    data_summary = data[data["frame_index"] == snapshot_index].reset_index(drop=True)
    data_summary["fulfillment_ratio"] = list(
        map(
            lambda x, y: round(x / (y + 1 / 1000), 4),
            data_summary["acc_fulfillment"],
            data_summary["acc_booking"]
        )
    )

    data_summary["port name"] = list(
        map(
            lambda x: index_name_conversion.loc[int(x[6:])][0],
            data_summary["name"]
        )
    )
    helper.render_h3_title("Select Top k:")
    selected_top_number = st.select_slider(
        label="",
        options=list(range(1, 6))
    )
    top_attributes = CIMItemOption.acc_info + ["fulfillment_ratio"]
    for item in top_attributes:
        helper.generate_by_snapshot_top_summary(
            "port name", data_summary, int(selected_top_number), item, snapshot_index
        )
Exemplo n.º 20
0
def step1():
    #--------------------------------------------------STEP 1--------------------------------------------------------------
    st.markdown('## Paso 1: Carga y preparación de los datos.')
    #Carga de archivo
    file = st.file_uploader('Cargá el archivo con los datos')

    if file is not None:
        file.seek(0)
        #Seleccionde separador
        sep = st.selectbox('Selecciona el separador de campos del archivo',
                           [None, ",", ";", "Tab"])
        if sep is not None:
            #Carga de los datos en un pd.dataframe
            data = pd.read_csv(file, sep=sep)
            #Se extraen las etiquetas de las clases
            labels = data.iloc[:, 2].unique()
            dictionary = {}
            #Se asignan nuevas etiquetas (numeros enteros)
            for i in range(len(labels)):
                dictionary[labels[i]] = np.float(i + 1)
            #Se confirma la carga correcta de los datos
            st.write(
                'Los datos fueron cargados **CORRECTAMENTE** :heavy_check_mark:'
            )
            #Se muestran los datos al tildar el checkbox
            if st.checkbox('Ver datos'):
                st.dataframe(data)
            #Se reemplazan los labels de los datos por numeros de 0 a N para poder manejar en np.ndarray
            data = data.replace(to_replace=dictionary)
            data = data.to_numpy()
            st.write("Hay ", data.shape[0], ' puntos cargados')
            #Selección de la proporcion de entrenamiento
            train_prop = st.selectbox(
                'Seleccione la proporción de datos de entrenamiento',
                [None, 0.7, 0.75, 0.8, 0.85])
            if train_prop is not None:
                st.write('La proporción de entrenamiento elegida es de: ',
                         train_prop, 'la de test es: ',
                         round(1 - train_prop, 2))
                #Selección del seed
                seed = st.select_slider(
                    'Seleccione un valor de seed para mezclar los datos y dividir el conjunto.',
                    list(range(1, 51)))
                #División del conjunto en training y test
                training, testing = split(data,
                                          train_prop,
                                          round(1 - train_prop, 2),
                                          seed=seed)
                st.write('El seed elegido para mezclar los datos es de: ',
                         seed)
                #Opción de ver la distribución de los conjuntos
                if st.checkbox('Ver Distribución de los conjuntos'):
                    st.write(
                        plot_training_test_distributions(training, testing))
                    st.write("Hay ",
                             len(training), " puntos de entrenamiento y ",
                             len(testing), " puntos de testeo.")
                    #Se ejecuta el paso 2.
                step2(data, training, testing, labels)
Exemplo n.º 21
0
def render_fn(state: AppState):
    import streamlit as st
    from streamlit_autorefresh import st_autorefresh

    st_autorefresh(interval=2000, limit=None, key="refresh")

    state.should_print = st.select_slider(
        "Should the Application print 'Hello World !' to the terminal:",
        [False, True],
    )
Exemplo n.º 22
0
def main():
    st.markdown("# Data visualization tool using Streamlit")

    st.title('My first app')

    st.text('Fixed width text')
    st.markdown('_Markdown_') # see *
    st.latex(r''' e^{i\pi} + 1 = 0 ''')
    st.write('Most objects') # df, err, func, keras!
    st.write(['st', 'is <', 3]) # see *
    st.title('My title')
    st.header('My header')
    st.subheader('My sub')

    st.sidebar.button('Hit me')
    st.checkbox('Check me out')
    st.radio('Radio', [1,2,3])
    st.selectbox('Select', [1,2,3])
    st.multiselect('Multiselect', [1,2,3])
    st.slider('Slide me', min_value=0, max_value=10)
    st.select_slider('Slide to select', options=[1,'2'])
    st.text_input('Enter some text')
    st.number_input('Enter a number')
    st.text_area('Area for textual entry')
    st.date_input('Date input')
    st.time_input('Time entry')
    st.file_uploader('File uploader')
    st.color_picker('Pick a color')

    # st.balloons()
    st.error('Error message')
    st.warning('Warning message')
    st.info('Info message')
    st.success('Success message')
    st.spinner()

    option = st.sidebar.selectbox('How would you like to be contacted?', ('Email', 'Home phone', 'Mobile phone'))
    st.sidebar.write('You selected:', option)

    test = st.sidebar.multiselect('Multiselect2', [1,2,3])
    st.sidebar.write('You selected:', test)
Exemplo n.º 23
0
    def test_format_func(self):
        """Test that format_func sends down correct strings of the options."""
        DAYS_OF_WEEK = [
            "Sunday",
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday",
        ]
        st.select_slider(
            "the label",
            value=1,
            options=[0, 1, 2, 3, 4, 5, 6],
            format_func=lambda x: DAYS_OF_WEEK[x],
        )

        c = self.get_delta_from_queue().new_element.slider
        self.assertEqual(c.default, [1])
        self.assertEqual(c.options, DAYS_OF_WEEK)
Exemplo n.º 24
0
    def test_range_session_state(self):
        """Test a range set by session state."""
        state = st.session_state
        state["colors"] = ("red", "orange")

        colors = st.select_slider(
            "select colors",
            options=["red", "orange", "yellow"],
            key="colors",
        )

        assert colors == ("red", "orange")
Exemplo n.º 25
0
def draw_all(key):
    st.write("""
        # Hello

        Hi **there!** This is `code`.

        ```
        This is block code.
        ```
    """)

    radio_markdown = """
    h2.  Select a number

    ---

    You have **3** choices! 
    """

    st.checkbox("Cool?", key=key, help='Press to confirm checkbox')
    st.radio("Pick a number", [1, 2, 3], key=key, help=radio_markdown)
    st.button("Click me!", key=key)
    st.slider("Pick a number", key=key)
    st.select_slider("Pick a number", [1, 2, 3], key=key)
    st.number_input("Pick a number", key=key)
    st.text_input("Pick a number", key=key)
    st.text_area("Pick a number", key=key)
    st.selectbox("Pick a number", [1, 2, 3], key=key)
    st.multiselect("Pick a number", [1, 2, 3], key=key)
    st.file_uploader("Pick a file", key=key)
    st.color_picker("Favorite color", key=key)
    with st.beta_expander("Expand me!"):
        st.write("hi")
    st.progress(0.6)
    st.json({"data": [1, 2, 3, 4]})
    st.dataframe({"data": [1, 2, 3, 4]})
    st.table({"data": [1, 2, 3, 4]})
    st.line_chart({"data": [1, 2, 3, 4]})
    st.help(st.write)
Exemplo n.º 26
0
    def test_widget_outputs_dont_alias(self):
        color = st.select_slider(
            "Select a color of the rainbow",
            options=[
                ["red", "orange"],
                ["yellow", "green"],
                ["blue", "indigo"],
                ["violet"],
            ],
            key="color",
        )

        ctx = get_report_ctx()
        assert ctx.session_state["color"] is not color
Exemplo n.º 27
0
def analysePublisher():

    num = st.select_slider(options=[5, 10, 15, 20, 25, 30],
                           label="Select the number of Publishers to show")
    st.header('Top Publishers By Release Count')
    st.plotly_chart(
        plotBar(analysis.getTopPublishersByCount(num),
                'Video Games Sales Publisher Data', 'Name Of Publisher',
                'Total sales in millions'))
    st.markdown("""
    ### In this graph, it shows the top publishers which are the highest in global sales and the top publisher is electronics arts which total sales is about 1350 million dollars and Electronic Arts is a leading publisher of games on Console, PC and Mobile. We exist to inspire the world through Play. Electronic Arts is a leading publisher of games on Console, PC and Mobile. EA Play FIFA 21 Madden NFL 21 Apex Legends Star Wars.
    # """)

    st.markdown("""
    ### The second top publishers is activision which global sales is about 950 million dollars and Activision Publishing, Inc. is an American video game publisher based in Santa Monica, California. It currently serves as the publishing business for its parent company, Activision Blizzard, and consists of several subsidiary studios. Activision is one of the largest third-party video game publishers in the world and was the top United States publisher in 2016.
     """)

    st.markdown("""
    """)
    st.markdown("""
    """)
    st.markdown("""
    """)
    st.markdown("""
    """)
    st.markdown("""
    """)
    st.markdown("""
    ---------
    """)
    st.header('Top Publishers By Total Sales')
    st.plotly_chart(
        plotBar(analysis.getTopPublishersBySum(num),
                'Total Sales of Publisher Data', 'Name Of Publisher',
                'Global sales in millions'))

    st.markdown(
        """ In this graph, it shows the top publishers which are the highest in total sales and the top publisher is Nintendo which total sales is about 1700 million dollars and 
Nintendo Co., Ltd. is a Japanese multinational consumer electronics and video game company headquartered in Kyoto. The company was founded in 1889 as Nintendo Karuta by craftsman Fusajiro Yamauchi and originally produced handmade hanafuda playing cards. After venturing into various lines of business during the 1960s and acquiring a legal status as a public company under the current company name, Nintendo distributed its first video game console, the Color TV-Game, in 1977. It gained international recognition with the release of the Nintendo Entertainment System in 1985.

The second top publishers is Electronics Arts and total sales is about 1100 million dollars and Electronic Arts is a leading publisher of games on Console, PC and Mobile.

    """)

    st.header('Top Publishers By Total Sales in Region')
    for region, name in analysis.getRegion():
        st.plotly_chart(
            plotBar(analysis.getTopPublishersBySumInRegion(num, region),
                    'Total Sales in ' + name, 'Top Publisher',
                    'Global sales in millions'))
Exemplo n.º 28
0
def display_plot(data, stats):
    """
    Create plots from function in plotting module
    
    """
    st.write(
        "### Use the slider to visualize your design in different seasons. Scroll down for plan view."
    )
    season = st.select_slider("Choose a season:",
                              options=['Spring', 'Summer', 'Autumn', 'Winter'])
    st.altair_chart(section_plot(data, stats, Season=f'{season}'),
                    use_container_width=False)
    st.altair_chart(density_plot(data, stats, Season=f'{season}'),
                    use_container_width=False)
    st.altair_chart(seasonality_chart(data, stats), use_container_width=False)
def run_app():
    st.title('Object Recognition App')
    selected_model = st.selectbox(
        'Select a Model : ',
        ['MobileNetV2', 'VoVNet-19', 'ResNet-50', 'ResNet-101'])
    remove_colors = st.select_slider('Remove Colors', options=[False, True])
    uploaded_img = st.file_uploader("Upload an image : ",
                                    type=['jpg', 'jpeg', 'png'])
    if uploaded_img is not None:
        img = read_image(uploaded_img)
        model = load_model(CONFIGS[selected_model], WEIGHTS[selected_model])
        outputs = predict(model, img)
        result_img = draw_predictions(img,
                                      outputs,
                                      remove_colors=remove_colors)
        st.image(result_img, caption='Processed Image', use_column_width=True)
Exemplo n.º 30
0
def bernoulli_ttest_ui(tech_note_path):
    '''The Two-sample Student's t-test - Bernoulli variables section. '''

    # Render the header. 
    with st.beta_container():
        st.title('Two-sample Student\'s t-test')
        st.header('Bernoulli variables')
        st.info('If the outcome variable is binary, for example, if you are testing for Click-through Rates (CTR) or customer retention rates, we suggest using a Chi-squared test. ')

    # Render input widgets
    with st.beta_container():
        col1, col2 = st.beta_columns([1, 1])
        with col1:  
            st.subheader('Group A')
            visitors_1 = st.number_input(
                'Visitors A: ', min_value=10, value=80000)
            conversions_1 = st.number_input(
                'Conversions A: ', min_value=0, value=1600)
            conf_level = st.select_slider('Confidence level: ', ('0.90', '0.95', '0.99'))
        with col2: 
            st.subheader('Group B')
            visitors_2 = st.number_input(
                'Visitors B: ', min_value=10, value=80000)
            conversions_2 = st.number_input(
                'Conversions B: ', min_value=0, value=1696)
            hypo_type = st.radio('Hypothesis type: ', ('One-sided', 'Two-sided'))
    
        # Assert visitors>=conversions
        try: 
            assert visitors_1 >= conversions_1 
        except: 
            raise ValueError('Visitors must be more the the converted. ')

        # Calculate statistics
        mu_1, mu_2, sigma_1, sigma_2 = bernoulli_stats(
            visitors_1, visitors_2, conversions_1, conversions_2)
        tstat, p_value, tstat_denom, pooled_sd, effect_size = scipy_ttest_ind_from_stats(
            mu_1, mu_2, sigma_1, sigma_2, visitors_1, visitors_2)
        observed_power = sm_tt_ind_solve_power(effect_size=effect_size, n1=visitors_1, n2=visitors_2, alpha=1-float(conf_level), power=None, hypo_type=hypo_type, if_plot=False)

        # Render the results
        ttest_plot(mu_1, mu_2, sigma_1, sigma_2, conf_level, tstat, p_value, tstat_denom, hypo_type, observed_power)

    # Render technical notes
    with st.beta_expander(label='Technical notes'):
        with open(tech_note_path, 'r') as tech_note:
            st.markdown(tech_note.read())