Beispiel #1
0
def test_constants():
    fig = px.scatter(x=px.Constant(1), y=[1, 2])
    assert fig.data[0].x[0] == 1
    assert fig.data[0].x[1] == 1
    assert "x=" in fig.data[0].hovertemplate

    fig = px.scatter(x=px.Constant(1, label="time"), y=[1, 2])
    assert fig.data[0].x[0] == 1
    assert fig.data[0].x[1] == 1
    assert "x=" not in fig.data[0].hovertemplate
    assert "time=" in fig.data[0].hovertemplate

    fig = px.scatter(
        x=[1, 2],
        y=[1, 2],
        symbol=["a", "b"],
        color=px.Constant("red", label="the_identity_label"),
        hover_data=[px.Constant("data", label="the_data")],
        color_discrete_map=px.IdentityMap(),
    )
    assert fig.data[0].marker.color == "red"
    assert fig.data[0].customdata[0][0] == "data"
    assert fig.data[1].marker.color == "red"
    assert "color=" not in fig.data[0].hovertemplate
    assert "the_identity_label=" not in fig.data[0].hovertemplate
    assert "symbol=" in fig.data[0].hovertemplate
    assert "the_data=" in fig.data[0].hovertemplate
    assert fig.layout.legend.title.text == "symbol"
Beispiel #2
0
def plot_icycle():
    # ----------
    df = px.data.tips()
    print(df.to_markdown())
    fig = px.icicle(df, path=[px.Constant("all"), 'day', 'time', 'sex'], values='total_bill')
    fig.update_traces(root_color="lightgrey")
    fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
    fig.show()

    # -----------
    df_tmp = cr_df_mem()
    df = df_tmp.filter(['host', 'process', 'pct'], axis=1)
    df.reset_index(inplace=True)
    print(df.to_markdown())
    fig = px.icicle(df, path=[px.Constant("all"), 'host', 'process'], values='pct')
    fig.update_traces(root_color="lightgrey")
    fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
    fig.show()
def get_treemap():
    fig = px.treemap(students,
                     path=[px.Constant(
                         'Berlin - Number of students per school-type and district'), 'Bezirk', 'Schulart'],
                     values='SchuelerInnen',
                     color='Schulart',
                     color_discrete_sequence=px.colors.qualitative.Bold)
    fig.update_layout(margin={"r": 16, "t": 16, "l": 16, "b": 16})
    return fig
Beispiel #4
0
def generateCountryInfectionTreemap():
    sample = covid_data.rename(columns={
        "location": "Kraj",
        "num_sequences_total": "Liczba przypadków"
    })
    fig = px.treemap(
        sample,
        path=[px.Constant('Liczba przypadków'), 'Kraj'],
        values='Liczba przypadków',
        hover_data=['Kraj'],
    )
    fig.show()
Beispiel #5
0
def tab4_content():
    fig1 = px.treemap(
        df_cost_rating,
        path=[px.Constant('All'), 'Rating text', 'Price range text'],
        values='Price range',
        title='Price range percentage according to Rating')
    fig2 = px.scatter(df_cost_rating[[
        'Rating text', 'Price range', 'Aggregate rating'
    ]].groupby('Rating text').mean().reset_index().sort_values('Price range'),
                      x='Price range',
                      y='Aggregate rating',
                      color='Rating text',
                      title='Rating and Cost Correlation')
    fig2.update_traces(marker=dict(size=12, line=dict(width=2)),
                       selector=dict(mode='markers'))
    fig3 = px.scatter(df_cost_rating,
                      x='Aggregate rating',
                      y='Average Cost for two in dollars',
                      color='Aggregate rating',
                      title='Average Cost for two in dollars vs Rating')
    fig3.update_traces(marker=dict(size=12, ), selector=dict(mode='markers'))
    return html.Div([
        dbc.Card(
            dbc.CardBody([
                html.H4("Restaurants", className="card-title"),
                html.H6("There is a good partion of Rating unrated",
                        className="card-text"),
                html.H6("There is correlation between Rating and cost",
                        className="card-text"),
                html.
                H6("Restaurants with high price range tend to have good rating",
                   className="card-text"),
            ]),
            className="mt-3",
        ),
        dbc.Card(
            dbc.CardBody(
                [dcc.Graph(id='bar-graph-restaurant-rating', figure=fig1)]),
            className="mt-3",
        ),
        dbc.Card(
            dbc.CardBody(
                [dcc.Graph(id='scatter-graph-cost-rating', figure=fig2)]),
            className="mt-3",
        ),
        dbc.Card(
            dbc.CardBody([dcc.Graph(id='scatter-graph-cost-two',
                                    figure=fig3)]),
            className="mt-3",
        ),
    ])
Beispiel #6
0
def update_graph_bottom(state_chosen):
    dff = df_2[df_2.state.isin(state_chosen)]
    # fig3 = px.bar(data_frame=dff, x='car_condition', y='count', color='state',barmode="stack",orientation='v')
    fig4 = px.treemap(dff,
                      path=[px.Constant('state'), 'state', 'car_condition'],
                      values='count',
                      color='state',
                      maxdepth=2)
    fig4.update_layout(
        title={
            'text': ' Treemap for Car Condition State-wise ',
            'y': 0.98,
            'x': 0.5,
            'xanchor': 'center',
            'yanchor': 'top'
        })
    return fig4
Beispiel #7
0
def update_area_graph(val_boro, val_species):
    filtered_df = df[(df['boroname'].isin(val_boro))
                     & (df['spc_common'].isin(val_species))]
    grouped_df = filtered_df.groupby(['boroname', 'spc_common',
                                      'health']).sum()
    grouped_again = grouped_df.groupby(
        level=0).apply(lambda x: 1 * x / float(x.sum())).reset_index().rename(
            columns={'count_tree_id': 'percent'})
    fig = px.treemap(grouped_again,
                     path=[px.Constant('New York City'), 'boroname', 'health'],
                     values='percent',
                     color='boroname',
                     hover_name='boroname',
                     title="Tree Health Proportion by Borough",
                     labels={"percent": "Percent:"})
    fig.update_traces(hovertemplate=None)
    fig.update_layout(hovermode="x")
    return fig
Beispiel #8
0
def main():
    """Func description"""
    r"""
    # The UK economy in charts

    This dashboard provides an overview of the UK economy.

    ## Output

    ### Indices of Production, Construction, and Services
    """
    plot_indices_of_output()
    st.write("""
    ### UK Blue Book breakdown of GDP
    """)
    df = ons_get_gdp_output_with_breakdown()
    fig = px.treemap(
        df,
        path=[px.Constant("GDP (£m, current prices)"), 0, 1, 2, 3],
        values="value",
        hover_data=["title"],
        color_discrete_sequence=px.colors.qualitative.Bold,
    )
    fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
    st.write(fig)

    st.write("""
    ## Labour Market

    ### Labour market indicators
    """)
    # Labour market indicators
    plot_labour_market_indicators()
    st.write("""
    ### Beveridge curve
    """)
    plot_beveridge_curve()
    st.write("""
    ### Phillips curve
    """)
    plot_phillips_curve()
def display_topic_cluster(n):

    df_text_bow = nlp.tfidf_matrix.toarray()
    bow_df = pd.DataFrame(df_text_bow)

    # Map the column names to vocabulary
    bow_df.columns = nlp.vectorizer.get_feature_names()
    bow_df['cluster'] = pd.DataFrame(clusters)

    word_freq = pd.DataFrame(
        bow_df[bow_df.cluster == n].sum().sort_values(ascending=False))
    word_freq.reset_index(level=0, inplace=True)
    word_freq.columns = ['word', 'frequency']

    if n > 0:
        word_freq.drop(index=[0], inplace=True)

    fig = px.treemap(word_freq[0:30],
                     path=[px.Constant(values[n]), 'word'],
                     values='frequency',
                     color='frequency',
                     hover_data=['frequency'],
                     color_continuous_scale=colors[n])
    return fig
Beispiel #10
0
df = pd.read_csv('airbnb_NYC_2019.csv')
fig = px.scatter_mapbox(df,
                        lat="latitude",
                        lon="longitude",
                        color="neighbourhood_group",
                        zoom=9)
fig.update_layout(mapbox_style="carto-positron")
figSunburst = px.sunburst(df,
                          path=['neighbourhood_group', 'room_type'],
                          values='price')
room_histogram = px.histogram(df, x="room_type", color="neighbourhood_group")
violin_fig = px.violin(df, y="price", x='neighbourhood_group', box=True)
treemap_fig = px.treemap(
    df,
    path=[px.Constant('nyc'), 'neighbourhood_group', 'neighbourhood'],
    values='price',
    hover_data=['neighbourhood'])

app.layout = html.Div([
    html.H1(children='Airbnb NYC',
            style={
                'font-family': 'Helvetica',
                'textAlign': 'center'
            }),
    html.Div([
        html.Label('Select a neighborhood', style={'font-family':
                                                   'Helvetica'}),
        dcc.Dropdown(id="dropdown-neighbourhood",
                     options=[{
                         'label': 'Brooklyn',
Beispiel #11
0
df_total = covid19_model.get_total()
df_total = dataframe_helper.clean_df_total(df_total)

fig_pie = px.pie(df_total, values='total', names='category')

## Current data (dataframe and charts)
df_current = covid19_model.get_current()
df_current = dataframe_helper.clean_df_current(df_current)

fig_choropleth = px.choropleth(df_current,
                               locations='country_code_iso3',
                               color='confirmed',
                               hover_name='location')

fig_treemap = px.treemap(df_current,
                         path=[px.Constant('world'), 'continent', 'location'],
                         values='confirmed',
                         color='active',
                         hover_data=['country_code_iso3'],
                         color_continuous_scale='RdBu',
                         color_continuous_midpoint=np.average(
                             df_current['active'],
                             weights=df_current['confirmed']))

fig_bubble = px.scatter(df_current,
                        x='deaths',
                        y='active',
                        size='confirmed',
                        color="continent",
                        hover_name='location',
                        log_x=True,
futurepred

# In[20]:

# Memasukan data dari df untuk di graph
futurepred['predicted'] = df['CASES.predicted']
futurepred['total'] = df['total_cases']

# In[21]:

# Plotly
fig = px.line(futurepred,
              x="date",
              y="predicted",
              color=px.Constant("Prediction"))
fig.add_bar(x=futurepred["date"], y=futurepred["total"], name="Total Cases")
fig.add_trace(
    go.Scatter(x=futurepred["date"],
               y=futurepred['y_fut'],
               name="Future Prediction",
               mode='lines+markers'))
fig.show()

# In[ ]:

# KKSI AI - SMKN 4 Bandung - Smart Helper
# Pembina:
# Ibu Tyas
# Berdasarkan Alphabet:
# Aldo
Beispiel #13
0
    df_expect=pd.DataFrame(
        dict(
            my_index_name=[0, 1, 0, 1],
            value=[1, 2, 3, 4],
            my_col_name=["a", "a", "b", "b"],
        )
    ),
)

# assigning a px.Constant: works
df = pd.DataFrame(dict(a=[1, 2], b=[3, 4]))
df.columns.name = "my_col_name"
df.index.name = "my_index_name"
append_special_case(
    df_in=df,
    args_in=dict(x=None, y=None, color=None, symbol=px.Constant(1)),
    args_expect=dict(
        x="my_index_name",
        y="value",
        color="my_col_name",
        symbol="symbol",
        orientation="v",
    ),
    df_expect=pd.DataFrame(
        dict(
            my_index_name=[0, 1, 0, 1],
            value=[1, 2, 3, 4],
            my_col_name=["a", "a", "b", "b"],
            symbol=[1, 1, 1, 1],
        )
    ),
ثقافة اليوم|Today's Culture|235
تقارير دولية|World Reports|4
تقارير رسومية|Graphical Reports|14
الأخبار الهامة|Important News|3
المجتمع الدولي|The International Community|1
أدب الجمعة|Friday Literature|1
الكاريكاتير|Caricature|1
تحقيقات وتقارير|Investigations and reports|2
ثقافة السبت|Saturday Education|2
اخر الثقافة|Latest news on culture|19
آخر الأخبار|Latest News|1
نجوم الأمس الرياضي|Yesterdays Sports Starts|1''')

NewsByCategoryfig = px.treemap(
    NewsByCategory.reset_index(),
    path=[px.Constant('Year'), 'Month', 'CategoryEn'],
    values='Total',
    color='Total',
    hover_data=['CategoryAR', 'Total'])
st.plotly_chart(NewsByCategoryfig, use_container_width=True)

# -- Chart #4 -- #

NewsByCategoryHisto = NewsByCategory.groupby(
    'CategoryEn')['Total'].sum().reset_index()
NewsByCategoryHistofig = px.histogram(NewsByCategoryHisto,
                                      x="CategoryEn",
                                      y="Total")
st.plotly_chart(NewsByCategoryHistofig, use_container_width=True)

# -- Chart #5 -- #
Beispiel #15
0
# -------------------------------------------------------------------Scatter pares de variables (MG3)

mg3 = px.scatter(df_cluster2,
                 x="recencia_meses",
                 y="avg_meses",
                 color="cluster_name",
                 title='Scatter pares de variables',
                 height=550)

#---------------------------------------------------------------------Treemap (MG4)

# Treemap clientes por canal/region/ciudad/cluster
mg4 = px.treemap(df_cluster2,
                 path=[
                     px.Constant('CLIENTES:  ' +
                                 str(df_cluster2["constante_cli"].sum())),
                     "canal_det", 'region', "cluster_name"
                 ],
                 values='constante_cli',
                 color='recencia_meses',
                 title="Visualizador de clientes: Canal/Región/Clúster",
                 color_continuous_scale='thermal_r',
                 height=700)

# --------------------------------------------------------------------3D Scatter variables clúster (MG5)

mg5 = px.scatter_3d(df_cluster2,
                    x="precio_promedio",
                    y="avg_meses",
                    z="visitas",
                    color="cluster_name",
                 y='Partner',
                 orientation='h',
                 text='Trade Value (US$)',
                 template="plotly_white")
    fig.update_traces(texttemplate='%{text:$,.2}')  #to format text on graphs
    fig.update_layout(template="seaborn",
                      yaxis={'categoryorder': 'total ascending'})
    st.plotly_chart(fig)

    ####
    import numpy as np

    #For treeplots
    st.subheader("Share of Exporting Countries to Pakistan (Values in US$)")
    fig = px.treemap(dfi,
                     path=[px.Constant(''), 'Partner'],
                     values='Trade Value (US$)',
                     hover_data=['Trade Value (US$)'])
    fig.data[0].textinfo = 'label+text+value+percent entry'
    st.plotly_chart(fig)

    st.subheader("Share of Exporting Countries to Pakistan (Values in US$)")
    fig = px.pie(dfi, values='Trade Value (US$)', names='Partner')
    fig.update_traces(textposition='inside')
    fig.update_layout(uniformtext_minsize=12, uniformtext_mode='hide')
    st.plotly_chart(fig)

    st.subheader("Share of Importing Countries from Pakistan (Values in US$)")
    fig = px.treemap(dfe,
                     path=[px.Constant(''), 'Partner'],
                     values='Trade Value (US$)',
Beispiel #17
0
print(continent_name)

df["con_code"] = df["Stadium"].apply(lambda x: pc.country_alpha2_to_continent_code(pc.country_name_to_country_alpha2(x, cn_name_format="default")) )


runs_df.dtypes


import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")
new_df = runs_df.groupby(["ground","Stadium","cont"]).sum()
new_df.reset_index(level=0, inplace=True)
new_df.reset_index(level=0, inplace=True)
new_df.reset_index(level=0, inplace=True)
fig = px.treemap(new_df, path=[px.Constant('world'), 'cont', 'Stadium', 'ground'], values='Runs',
                  color='Runs', hover_data=['Runs'])
fig.show()

img_bytes = fig.to_image(format="png")


#tree map

#Runs
new_df = runs_df.groupby(["ground","Stadium","cont"]).sum()
new_df.reset_index(level=0, inplace=True)
new_df.reset_index(level=0, inplace=True)
new_df.reset_index(level=0, inplace=True)

fig = px.treemap(new_df, path=[px.Constant('world'), 'cont', 'Stadium','ground'],
Beispiel #18
0
from data_store import dataframe as df
import plotly.express as px
import pandas as pd
from math import log

df = df[df['Date_reported'] == pd.Timestamp.today().normalize() - pd.Timedelta(days = 1)]
df = df[['Country', 'Region', 'New_cases', 'Population']]

fig = px.treemap(df,
                 custom_data = df.columns,
                 path = [px.Constant('World'), 'Region', 'Country'],
                 values = 'Population',
                 color = df['New_cases'].apply(lambda new_cases:log(new_cases) if new_cases > 1 else new_cases),
                 color_continuous_scale = 'ylgnbu',
                 #hover_data = ['Population', 'New_cases'],
                 labels = {'New_cases':'Cases', 'color':'Cases'},
                 title = 'Global Distribution of New Cases by Region')
fig.update_layout(margin = {'r':0,'t':60,'l':10,'b':10})
fig.update_traces(hovertemplate = 'Region: %{customdata[1]} <br>\
                                   Population: %{customdata[3]} <br>\
                                   New Cases: %{customdata[2]}')
    def TreeMap(
        self,
        df,
        color,
        values,
        title,
        reverse_scale,
        log,
        midpoint,
        format,
        context_keys,
        value_in_text=True,
        **kwargs,
    ):
        """Plots a treemap to view performance over multiple context keys

        Parameters
        ----------
        color : str
            The column to set as the color of the squares
            One out of:
            {responsecount, responsecount_log, positives,
            positives_log, percentage_without_responses,
            performance_weighted, successrate}
        by : str
            The column to set as the size of the squares
        value_in_text : str
            Whether to print the values of the squares in the squares
        midpoint : Optional[float]
            A parameter to assert more control over the color distribution
            Set near 0 to give lower values a 'higher' color
            Set near 1 to give higher values a 'lower' color
            Necessary for, for example, Success Rate, where rates lie very far apart
            If not supplied in such cases, there is no difference in the color
            between low values such as 0.001 and 0.1, so midpoint should be set low
        to_html : bool
            Whether to write image to html, with title file_title at path file_path
        file_title : Optional[str]
            The title of the image when written to html
        file_path : Optional[str]
            The location the file will be written when written to html
        query : Union[str, dict]
            The query to supply to _apply_query
            If a string, uses the default Pandas query function
            Else, a dict of lists where the key is column name in the dataframe
            and the corresponding value is a list of values to keep in the dataframe
        show_each : bool
            Whether to show each file when multiple facets are used
        facets : Optional[Union[list, str]]
            Whether to create a chart for multiple facets or subsets.
            For example, if facets == 'Channel', a bubble plot is made for each channel
            Depending on show_each, every chart is either shown or not
            If more than one facet is visualised, they are returned in a list

        Returns
        -------
        px.Figure
        """

        context_keys = [px.Constant("All contexts")] + context_keys
        colorscale = kwargs.pop("colorscale",
                                ["#d91c29", "#F76923", "#20aa50"])

        range_color = None

        if color == "Performance weighted mean":
            colorscale = [
                (0, "#d91c29"),
                (kwargs.get("midpoint", 0.01), "#F76923"),
                (kwargs.get("acceptable", 0.6) / 2, "#20aa50"),
                (0.8, "#20aa50"),
                (1, "#0000FF"),
            ]
            range_color = kwargs.get("range_color", [0.5, 1])

        elif log:
            color = np.where(
                np.log(df[color]) == -np.inf,
                0,
                np.log(df[color]),
            )
        else:
            color = df[color]

        if midpoint is not None:
            midpoint = np.quantile(color, midpoint)
            colorscale = [
                (0, colorscale[0]),
                (midpoint, colorscale[1]),
                (1, colorscale[2]),
            ]

        hover_data = {
            "Model count": ":.d",
            "Percentage without responses": ":.0%",
            "Response Count sum": ":.d",
            "Success Rate mean": ":.3%",
            "Performance weighted mean": ":.0%",
            "Positives sum": ":.d",
        }

        fig = px.treemap(
            df,
            path=context_keys,
            color=color,
            values=values,
            title=f"{title}",
            hover_data=hover_data,
            color_continuous_scale=colorscale,
            range_color=range_color,
        )
        fig.update_coloraxes(reversescale=reverse_scale)

        if value_in_text:
            fig.update_traces(text=fig.data[0].marker.colors.round(3))
            fig.data[0].textinfo = "label+text"
            if format == "%":
                fig.data[0].texttemplate = "%{label}<br>%{text:.2%}"

        if kwargs.get("min_text_size", None) is not None:
            fig.update_layout(uniformtext_minsize=kwargs.pop("min_text_size"),
                              uniformtext_mode="hide")
        fig = self.post_plot(fig, name="TreeMap", **kwargs)
        return fig
Beispiel #20
0
def plot_treemap(data, title, path, top_level, file_name, year, color_col,
                 write, write_folder, publish, publish_prefix):
    data = data.copy()

    path = [px.Constant(top_level)] + path

    # Filter by year.
    data = data[data['Academic Yr'] == year]

    # Group by columns in path.
    cols = path[1:]
    filtered = group(data, cols)

    # Calculate Percentages.
    total = data.groupby('Academic Yr').sum()['Headcount']
    calculate_percentage = lambda row: 100 * (row.get('Headcount') / total)
    filtered['Percentage'] = filtered.apply(calculate_percentage, axis=1)

    # Convert Admit Rate into Percentage.
    filtered['Admit Rate'] = filtered['Admit Rate'].apply(lambda x: x / 100)

    if color_col == 'Headcount':
        fig = px.treemap(filtered,
                         path=path,
                         values='Headcount',
                         color=color_col,
                         hover_data={
                             'Admit Rate': True,
                             'Percentage': True
                         },
                         color_continuous_scale='BuGn')

    elif color_col == 'Admit Rate':
        fig = px.treemap(
            filtered,
            path=path,
            values='Headcount',
            color=color_col,
            color_continuous_scale='OrRd',
            hover_data={
                'Admit Rate': True,
                'Percentage': True
            },
        )

    fig.update_layout({'font_family': 'Avenir Next', 'font_color': 'black'})
    fig.update_layout(margin={'b': 10})
    fig.update_layout(title={
        'text': title,
        'x': 0.5,
        'y': 0.97,
        'xanchor': 'center',
        'yanchor': 'top'
    })

    fig._data_objs[0].hovertemplate = '%{id}<br><br>' + \
                                      'Headcount: %{value}<br>' + \
                                      'Fraction of Total: %{percentRoot:.2f}<br>' + \
                                      'Fraction of Parent: %{percentParent:.2f}<br>' + \
                                      'Admit Rate: %{customdata[0]:.2f}'

    if not write: fig.show()
    else:
        fig.write_html(write_folder + file_name + '.html',
                       include_plotlyjs='cdn')
    if publish:
        py.plot(fig, filename=publish_prefix + file_name, auto_open=False)
Beispiel #21
0
import pandas as pd
import plotly.express as px  # Plotly version >= 5.0

# data from: https://data.virginia.gov/Education/Bills-of-Sale-of-Enslaved-Individuals-1718-1862-/j2xt-sjy7
df = pd.read_csv(
    "https://raw.githubusercontent.com/Coding-with-Adam/Dash-by-Plotly/master/Plotly_Graphs/Icicle/Bills_of_Sale_of_Enslaved_Individuals__1718-1862.csv"
)
print(df.head()[['Period', 'Locality']])

fig = px.icicle(df,
                path=[px.Constant("all"), 'Period', 'Locality'],
                values='Slaves')

# fig = px.icicle(df, path=[px.Constant("all"), 'Period', 'Locality'],
#                 values='Slaves', color='Locality')

# fig = px.icicle(df, path=[px.Constant("all"), 'Period', 'Locality', 'Gender'],
#                 values='Slaves', color='Gender')

# fig = px.icicle(df, path=[px.Constant("all"), 'Period', 'Locality', 'Enslaver_Buyer'],
#                 values='Slaves')

# fig = px.icicle(df, path=[px.Constant("all"), 'Period', 'Locality', 'Enslaver_Buyer'],
#                 values='Slaves', color='Age')

# fig = px.icicle(df, path=[px.Constant("all"), 'Period', 'Locality', 'Enslaver_Buyer'],
#                 values='Slaves', color='Age', color_continuous_scale='RdBu')

# fig = px.icicle(df, path=[px.Constant("all"), 'Period', 'Locality'],
#                 values='Slaves', color='Locality')
# fig.update_traces(root_color="lightgrey", tiling=dict(orientation='h', flip='x'))
Beispiel #22
0
     },
     "widgetParams": {
         "title": "Gapminder",
         "icon": "fa fa-globe",
         "caption": "Life Expectation"
     }
 },
 {
     "id": "gapminder-treemap",
     "df_type": "gapminder",
     "text": "Life Expectation Tree",
     "df": df_gapminder,
     "dfTrafos": lambda x: x.query("year == 2007"),
     "plotter": px.treemap,
     "plotParams": {
         "path": [px.Constant('world'), 'continent', 'country'],
         "values": 'pop',
         "color": 'lifeExp',
         "hover_data": ['iso_alpha'],
         "title": "Life Expectation"
     },
     "widgetParams": {
         "title": "Gapminder",
         "icon": "fa fa-globe",
         "caption": "Life Expectation Tree"
     }
 },
 {
     "id": "gapminder-choropleth",
     "df_type": "gapminder",
     "text": "Life Expectation Map",
Beispiel #23
0
fig1.update_layout(title_text = "Bar plot showing total runs in an over made by the selected player")
st.plotly_chart(fig1)

fig2 = px.scatter_matrix(new_data, dimensions=["wide_runs", "bye_runs", "legbye_runs", "noball_runs"], color="ball")
fig2.update_layout(title_text= "Scatter plot showing data on different parameters in all the matches played by the selected player")
st.plotly_chart(fig2)

fig3 = px.scatter(new_data, x="over", y="penalty_runs", size="batsman_runs", color="ball",
           hover_name="batsman", log_x=True, size_max=60)
fig3.update_layout(title_text= "This graph shows zero penalty runs in all the matches played by the selected player")           
st.plotly_chart(fig3)

st.markdown("### This Data visualization is from 'Matches dataset' of IPL matches played by MS Dhoni")
st.markdown("note:This Data visualization is already selected for 1 Player")

fig4 = px.treemap(Cdata.query('season == 2017'), path=[px.Constant('player_of_match'), 'venue', 'winner'], values = 'win_by_runs', color = 'player_of_match', hover_data= ['date'])
fig4.update_layout(title_text = "Tree map showing players of the matches in different IPL teams")
st.plotly_chart(fig4)

fig5 = px.area(Cdata[(Cdata.player_of_match == "MS Dhoni")], x = "season" , y = "win_by_wickets", color="date", line_group="city")
fig5.update_layout(title_text = "Area chart showing matches won by MS Dhoni in different seasons")
st.plotly_chart(fig5)

fig6 = px.scatter(Cdata[(Cdata.player_of_match == "MS Dhoni")], x= "win_by_runs", y = "season", size = "win_by_runs", color = "venue" , hover_name = "player_of_match", log_x =True, size_max = 60)
fig6.update_layout(title_text="Scatter plot showing wins_by_runs data over a season per se by MS Dhoni")
st.plotly_chart(fig6)

fig7 = px.density_heatmap(Cdata[(Cdata.player_of_match == "MS Dhoni")], x = "season", y = "city", marginal_x = "rug", marginal_y="histogram")
fig7.update_layout(title_text = "Density Heat Map depicting matches played in different cities over the years")
st.plotly_chart(fig7)
Beispiel #24
0
def treemap(metrics):
    try:
        if metrics == "Runs":
            st.header("Stadium-wise Runs Scored")
            new_df = runs_df.groupby(["ground","Stadium","cont"]).sum()
            new_df.reset_index(level=0, inplace=True)
            new_df.reset_index(level=0, inplace=True)
            new_df.reset_index(level=0, inplace=True)
            
            fig = px.treemap(new_df, path=[px.Constant('world'), 'cont', 'Stadium','ground'],
                             labels={'labels':'Stadium' ,'parent' : 'continent', 'Stadium' : 'Country'}, values='Runs',color = 'Stadium', height=600,width= 700)
            fig.data[0].textinfo = 'label+text'
            fig.data[0].hovertemplate = '%{label}<br>Runs = %{value}'
            fig.update_traces(marker_colors=["pink", "royalblue", "yellow", "orange", "lightblue"])
            return fig
        elif metrics == "Matches":
            st.header("Stadium-wise Macthes Played")
            new_df = runs_df.groupby(["ground","Stadium","cont"]).count()
            new_df.reset_index(level=0, inplace=True)
            new_df.reset_index(level=0, inplace=True)
            new_df.reset_index(level=0, inplace=True)
            
            fig = px.treemap(new_df, path=[px.Constant('world'), 'cont', 'Stadium','ground']
                             , values='Runs',color = 'Stadium', height=600,width= 700)
            fig.data[0].textinfo = 'label+text'
            fig.data[0].hovertemplate = '%{label}<br>Matches = %{value}'
            fig.update_traces(marker_colors=["pink", "royalblue", "yellow", "orange", "lightblue"])
            return fig
        elif metrics == "Not Out's":
             st.header("Stadium-wise Not Outs")    
             new_df2 = runs_df.groupby(["Stadium"]).count()
             new_df1 = runs_df.groupby(["Stadium"]).sum()
             new_df2["OUT"] = new_df2["OUT"] - new_df1["OUT"]
             new_df = new_df2
             new_df.reset_index(level=0, inplace=True)
             fig = px.treemap(new_df, path=[px.Constant('world'), 'Stadium'],
                             labels={'labels':'Stadium' ,'parent' : 'continent', 'Stadium' : 'Country'}, values='OUT', height=600,width= 700)
             fig.data[0].textinfo = 'label+text'
             fig.data[0].hovertemplate = '%{label}<br>Not Outs = %{value}'
             fig.update_traces(marker_colors=["pink", "royalblue", "yellow", "orange", "lightblue"])
             return fig
        elif metrics == "Average":
             st.header("Stadium-wise Average")
             new_df = runs_df.groupby("Stadium").sum()
             new_df["avg"] = new_df["Runs"]/new_df["OUT"]
             for n, i in zip(new_df.index,new_df["avg"]):
                 if i == float("inf"):
                     inf = new_df.loc[n]["Runs"]*2
                     new_df = new_df.replace(to_replace =[float("inf")],  
                                        value =inf)
             new_df.reset_index(level=0, inplace=True)        
             fig = px.treemap(new_df, path=[px.Constant('world'), 'Stadium'],
                             labels={'labels':'Stadium' ,'parent' : 'continent', 'Stadium' : 'Country'}, values="avg",color = 'Stadium', height=600,width= 700)
             fig.data[0].textinfo = 'label+text'
             fig.data[0].hovertemplate = '%{label}<br>Avg = %{value:.4s}'
             fig.update_traces(marker_colors=["pink", "royalblue", "yellow", "orange", "lightblue"])
             return fig
        elif metrics == "Sixers":
             st.header("Stadium-wise Sixers Scored")
             new_df = runs_df.groupby(["ground","Stadium","cont"]).sum()
             new_df.reset_index(level=0, inplace=True)
             new_df.reset_index(level=0, inplace=True)
             new_df.reset_index(level=0, inplace=True)
            
             fig = px.treemap(new_df, path=[px.Constant('world'), 'cont', 'Stadium','ground'],
                             labels={'labels':'Stadium' ,'parent' : 'continent', 'Stadium' : 'Country'}, values="6's",color = 'Stadium', height=600,width= 700)
             fig.data[0].textinfo = 'label+text'
             fig.data[0].hovertemplate = '%{label}<br>Sixs = %{value}'
             fig.update_traces(marker_colors=["pink", "royalblue", "yellow", "orange", "lightblue"])
             return fig
        elif metrics == "Strike rate":
            st.header("Stadium-wise Batsman Strike rate")
            new_df = runs_df.groupby(["Stadium"]).sum()
            new_df["SR"] = (new_df["Runs"]/new_df["Balls"])*100
            new_df.reset_index(level=0, inplace=True)
            new_df.reset_index(level=0, inplace=True)
            new_df.reset_index(level=0, inplace=True)
          
            fig = px.treemap(new_df, path=['Stadium'],
                           labels={'labels':'Stadium' ,'parent' : 'continent', 'Stadium' : 'Country'}, values="SR",color = 'Stadium', height=600,width= 700)
            fig.data[0].textinfo = 'label+text'
            fig.data[0].hovertemplate = '%{label}<br>SR = %{value:.4s}'
            fig.update_traces(marker_colors=["pink", "royalblue", "yellow", "orange", "lightblue"])
            return fig
        elif metrics == "Fours":
             st.header("Stadium-wise Fours Scored")
             new_df = runs_df.groupby(["ground","Stadium","cont"]).sum()
             new_df.reset_index(level=0, inplace=True)
             new_df.reset_index(level=0, inplace=True)
             new_df.reset_index(level=0, inplace=True)
            
             fig = px.treemap(new_df, path=[px.Constant('world'), 'cont', 'Stadium','ground'],
                             labels={'labels':'Stadium' ,'parent' : 'continent', 'Stadium' : 'Country'}, values="4's",color = 'Stadium', height=600,width= 700)
             fig.data[0].textinfo = 'label+text'
             fig.data[0].hovertemplate = '%{label}<br>Fours = %{value}'
             fig.update_traces(marker_colors=["pink", "royalblue", "yellow", "orange", "lightblue"])
             return fig
    except:  
        animals=['No Macthes Played']
        fig = go.Figure(data=[
        go.Bar(x=animals, y=[0]),])
        return fig