Search code examples
pythonjupyter-notebookplotlyseabornhistogram

Plotly library is plotting blank space while seaborn is plotting correctly


enter image description here

My code

import seaborn as sns
import plotly.express as px

sns.histplot(df_user_test_session_question_accuracy, x="QuestionAccuracy")


df = df_user_test_session_question_accuracy
fig = px.histogram(df, x="QuestionAccuracy",
                   title='Histogram of QuestionAccuracy ',
                   opacity=0.8,
                   log_y=True, # represent bars with log scale
                   color_discrete_sequence=['indianred'] # color of histogram bars
                   )
fig.show()

Here I am running both seaborn and plotly plot in a separate kernel , seaborn is plotting expected plots but plotly just giving a large blank space with no plots, What is the error behind it I want to use plotly for its interactiveness, any help is appreciated


Solution

  • seaborn uses np.histogram(). If you want same calculation framework, use it and effectively plot using go.Scatter()

    import seaborn as sns
    import plotly.express as px
    import plotly.graph_objects as go
    import pandas as pd
    import numpy as np
    
    df_user_test_session_question_accuracy = pd.DataFrame(
        {
            "QuestionId": np.arange(0, 18000),
            "QuestionAccuracy": np.random.uniform(0, 1, 18000),
        }
    )
    
    # use consistent number of bins across various plots...
    BINS = 25
    
    sns.histplot(df_user_test_session_question_accuracy, x="QuestionAccuracy", bins=BINS)
    
    
    df = df_user_test_session_question_accuracy
    fig = px.histogram(
        df,
        x="QuestionAccuracy",
        title="Histogram of QuestionAccuracy ",
        opacity=0.8,
        nbins=BINS,
        log_y=True,  # represent bars with log scale
        color_discrete_sequence=["indianred"],  # color of histogram bars
    )
    fig.show()
    
    # use same mechanisim as seaborn to calculate histrogram bins
    y, x = np.histogram(df["QuestionAccuracy"], bins=BINS)
    x = np.round(x, 2)
    go.Figure(go.Scatter(y=y, line_shape="hvh", fill="tozeroy")).update_xaxes(
        tickmode="array",
        tickvals=np.linspace(0, len(x), 6),
        ticktext=np.linspace(x[0], x[-1], 6),
    ).show()