Search code examples
pythondataframeplotlyhistogramsubplot

How to subplot histogram using multiple columns with plotly?


So I have data that I transformed up to this point (pic below). How can I now subplot histograms that will show me the programming languages used per job? I tried with just 2 columns at first:

px.histogram(languages_job_title_grouped, x =['Python','SQL'], facet_col = 'Role', facet_col_wrap = 4,height = 1000)

But it didn't work - it plots histogram by job, but the bars are the same for every role (2nd picture below). How can I do it the right way?

enter image description here

enter image description here


Solution

  • From the context of your question, it seems like you are looking for a bar plot instead.

    I.e. If I understand correctly, you are starting from a dataframe equivalent to

    example_df

    and trying to plot bar_plot

    where the facets are the index, the x-axis is each column, and the bar heights are the values in the dataframe.

    The code that generates this is:

    import pandas as pd
    import plotly.express as px
    
    df = pd.DataFrame(
        [[0.1, 0.3, 0.5], [0.2, 0.1, 0.8], [0.5, 0.3, 0.9]],
        columns=["a", "b", "c"],
        index=["index1", "index2", "index3"],
    )
    
    px.bar(
        df.melt(ignore_index=False).reset_index(),
        facet_col="index",
        x="variable",
        y="value",
        barmode="group",
    )
    

    The key being to reformat your DataFrame using melt before trying to plot with plotly.express.