Search code examples
pythonpandasplotly-express

Categorical Scatter Plot with Plotly


I am trying to draw a scatter plot with numerical x-values that are discrete. The problem is that Plotly interprets the values as continuous and the resulting dots are not evenly spaced. In Seaborn I could solve this problem by converting the x-values to str, but this doesn't work in Plotly. Any solutions? MWE below:

4489058292    0.60
4600724046    0.26
6102975308    0.19
6122589624    0.10
4467367136    1.67
6008680375    2.50
4588967207    0.21
4941295226    0.34
4866979526    0.18
4906915418    0.38
test_df = pd.read_clipboard(sep="\s+", names=["ID", "Value"], index_col=0)

fig = px.scatter(
    test_df,
    x=test_df.index.astype(str),
    y=test_df,
)

fig.update_layout(showlegend=False)

Solution

  • IIUC, in the update_layout, you can specify the xaxis_type to be category like:

    fig = px.scatter(
        test_df,
        x=test_df.index, #no need of str here
        y=test_df,
    )
    
    fig.update_layout(showlegend=False, 
                      xaxis_type='category') #add this