Search code examples
pythonpandasplotlystreamlit

how to implement custom plotly bubble chart


I new to plotly library , I want to visualize a dafarame into a plotly Bubble chart.

here's the code :

import plotly.graph_objects as go
import plotly.graph_objects as px 
import streamlit as st
import pandas as pd

data = {'x': [1.5, 1.6, -1.2],
        'y': [21, 16, 46],
        'circle-size': [10, 5, 6],
        'circle-color': ["red","blue","green"]
        }
# Create DataFrame
df = pd.DataFrame(data)
st.dataframe(df)
fig = px.scatter(df, x="x", y="y", color="circle-color",
                 size='circle-size')
fig.show()
st.plotly_chart(fig)

I have problems, the first one is how to plug the dataframe(df) with plotly to see the data ? and the second I'm lookng to implement a custom bubble chart, something with colors with negative values like this : enter image description here

can anyone help pleas to solve these problems ? thnaks


Solution

  • You were not far from getting it right. I just made a few adjustments to your code:

    import streamlit as st
    import plotly.express as px
    import pandas as pd
    
    st.title("Custom Bubble Chart with Negative Value Highlighting")
    
    data = {'x': [1.5, 1.6, -1.2, -2.0, 2.3, -3.5],
            'y': [21, 16, 46, 30, 10, 55],
            'circle-size': [10, 5, 6, 8, 12, 9]}
    
    df = pd.DataFrame(data)
    
    df["color"] = df["x"].apply(lambda val: "red" if val < 0 else "blue")
    
    st.dataframe(df)
    
    fig = px.scatter(df, x="x", y="y", 
                     size="circle-size",
                     color="color",
                     color_discrete_map={"red": "red", "blue": "blue"},
                     title="Bubble Chart (Red = Negative X, Blue = Positive X)")
    
    st.plotly_chart(fig)
    
    

    which gives

    streamlit image