Search code examples
pythonpandasplotly

Pandas Plotly assign colors by label


I'm plotting 7 different DataFrames and I'm trying to assign them color according to my labels but when I do it I get the error

ValueError: All arguments should have the same length. The length of argument color is 7, whereas the length of previously-processed arguments ['x', 'wide_variable_0', 'wide_variable_1', 'wide_variable_2', 'wide_variable_3', 'wide_variable_4', 'wide_variable_5', 'wide_variable_6'] is 73

I'm lost because why would he try to label according to the x axis? That's the only one with 73 values. Also I don't know where do those wide_variables come from.

This is the code I'm using, it works fine unless I try to assign colors:

fig = px.line(df, 
        y = [ejey.sin_vac_uci, ejey2.una_dosis_uci, ejey3.dos_dosis_uci, ejey4.dos_dosis_comp_uci, ejey5.dosis_unica_uci, ejey6.dosis_unica_comp_uci,
         ejey7.dosis_ref_comp_uci],
        x = df.semana_epidemiologica, 
         title='Incidencia en UCI',
         color=df.columns[8:], 
         )
    fig.show()

When I print(df.columns[8:]) I see exactly what I want: An array of 7 different labels but for some reason python is expecting 73..


Solution

  • The field color is used to identify colors for each data point. More information here. As you have each of your line data in separate columns, you can use color_discrete_sequence to set colors of each line. As you have not provided any data, am using random data to show an example. Hope this is what you are looking for.

    df = pd.DataFrame({'rand1': random.sample(range(1, 50), 20),
                        'rand2': random.sample(range(1, 30), 20),
                        'rand3': random.sample(range(1, 30), 20),
                        'rand4': random.sample(range(1, 30), 20),
                        'rand5': random.sample(range(1, 30), 20),
                        'myX' : range(20)})
    fig = px.line(df, 
            y = ['rand1', 'rand2', 'rand3', 'rand4', 'rand5'],
                  x= 'myX', color_discrete_sequence=["yellow", "blue", "pink", "skyblue", "red"])
    fig.update_layout(legend_title_text='Super Graph')
    fig.show()
    

    Output Graph enter image description here