Paul Wilson
Paul Wilson

Reputation: 560

How to stop Plotly Scatter from creating non-existing X values

I've tried googling this and have implemented all the supposed fixes I've found: Setting tickvals and connectgaps but it hasn't resolved the issue.

I have a dataset of about 100 rows with property transaction values from 1998, 1999, and 2020. However, Plotly insists on creating every year between 1999 and 2020 even though it doesn't exist in the dataset.

Here is my chart code:

def scatter(df):
    """
    Must take in a df with property_type, year, price_paid
    """
    figs = []

    for prop_type in df['property_type'].unique():
        df_filt = df[df['property_type'] == prop_type]
        figs.append(
            go.Scatter(x=df_filt['year'],
                       y=df_filt['price_paid'],
                       mode='markers',
                       marker=dict(
                           size=15,
                           opacity=0.5,
                           line=dict(
                               width=1,
                               color='darkSlateGrey'
                           )
                       ),
                       name=prop_type,
                       connectgaps=True)
        )

    layout = go.Layout(width=1000,
                       height=600)

    fig = go.Figure(data=figs, layout=layout)

    fig.update_xaxes(tickmode='array',
                     tickvals=[n for n in range(len(df_filt['year'].unique()))],
                     ticktext=[n for n in df_filt['year'].unique()])

    chart = pyo.plot(fig, output_type='div', include_plotlyjs=True)

    return chart

However here is what it shows..

enter image description here

All help appreciated!

Thanks

Upvotes: 2

Views: 280

Answers (1)

s3dev
s3dev

Reputation: 9721

The solution might be (and per your comment, definitely is) as simple as adding the following to the xaxis layout:

'type': 'category'

Upvotes: 2

Related Questions