简体   繁体   中英

Color Dictionary is not respected by Plotly in Python

I'm creating a dashboard using Streamlit, and I'm finding something odd, my plot is visualizing a clustering algorithm with an interactive number input for the number of clusters. So I would expect that if I have 2 inputs, I will always get the same values as a color for my marker.

However, every time I interact with the website the color changes, and I have to get those colors for my clusters.

def plot_model(cluster_model):
    cluster_color_dict = {
        1:'yellow',
        2:'CornflowerBlue',
        3:'orange',
        4:'green',
        5:'black',
        6:'fuchsia',
        7:'red',
        8:'aqua',
        9:'deepskyblue',
        10:'greenyellow'
    }

    fig = px.scatter_3d(cluster_model,
                    x='NPHI',
                    y='RHOZ',
                    z='GR',
                    color='Clusters',
                    color_continuous_scale=list(cluster_color_dict.values()))

    fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
    fig.update_traces(marker_size=3)
    return fig

Anyway, I think maybe one way is to simply generate an array of numbers to trim the length of the dictionary, such that it always has the colors requested by the user?

The problem I had is that the dictionary contains 10 elements, but the number of elements pass on to the function to create the graph is less, so if I want to have consistent colors, I just have to pass the number of elements and then filter the dictionary, that way I always get the same color scheme in my graph:

def plot_model(cluster_model,k):
    template = {
        1:'yellow',
        2:'CornflowerBlue',
        3:'orange',
        4:'green',
        5:'black',
        6:'fuchsia',
        7:'red',
        8:'aqua',
        9:'deepskyblue',
        10:'greenyellow'
    }
    i,j = 1,k
    cluster_color_dict = {}
    for k,v in template.items():
        if int(k) >= i and int(k) <= j:
            cluster_color_dict[k] = v




    fig = px.scatter_3d(cluster_model,
                    x='NPHI',
                    y='RHOZ',
                    z='GR',
                    color='Clusters',
                    color_continuous_scale=list(cluster_color_dict.values()))

    fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
    fig.update_traces(marker_size=3)
    return

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM