mitra mirshafiee
mitra mirshafiee

Reputation: 483

How to shorten and show only a part of text in plotly express axis?

I'm trying to output a graph that has ids on its x-axis and numbers on its y. Now I'm having difficulty seeing the graph itself as the ids are too long. I don't want to remove the whole ids and I just need to have for example the last few letters of each. Does anyone know if Plotly express has anything like using a regex for the labels? enter image description here

Upvotes: 2

Views: 4755

Answers (1)

Sander van den Oord
Sander van den Oord

Reputation: 12818

To shorten the tick labels of your x-axis, you could either change the id's of your column beforehand by changing the dataframe, or you could use .update_layout() to change your tick labels afterwards.

See also: https://plotly.com/python/tick-formatting/

This question + answer is related: Plotly: How to set custom xticks

Example code:

import uuid
import numpy as np
import pandas as pd

import plotly.express as px


# generating some sample data and dataframe
length = 4
data = {
    'colA': [str(uuid.uuid4()) for i in range(length)],
    'colB': np.random.normal(size=length)
} 
df = pd.DataFrame(data)

# create scatter plot
fig = px.scatter(data_frame=df, x='colA', y='colB', width=600, height=400)

# overwrite tick labels    
fig.update_layout(
    xaxis = {
     'tickmode': 'array',
     'tickvals': list(range(length)),
     'ticktext': df['colA'].str.slice(-6).tolist(),
    }
)

Resulting plot:

using update_layout() to adjust tick labels

Upvotes: 1

Related Questions