how to control max length of colum names graph in plotly dash

Question:

i have a code like that

import plotly.express as px

df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
fig = px.bar(df, y='pop', x='country', text='pop')
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')
fig.show()

and it builds me this diagram
enter image description here

how to make max length on colums name?

Asked By: MaxuwkaPlus

||

Answers:

I think there is a very similar question & answer here. Adapted to your case, you could chose to keep only the first n letters of the column name. It would look like the following:

import plotly.express as px
# Data
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
# Figure
fig = px.bar(df, y='pop', x='country', text='pop')
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')

# The modification: overwrite tick labels    
# Choose the number of letters to keep
n = 7
fig.update_layout(
    xaxis = {
     'tickmode': 'array',
     'tickvals': df.country.unique().tolist(),
     'ticktext': [i[:n] for i in df.country.unique().tolist()],
    }
)
fig.show()

For n=7 it produces:
enter image description here

Answered By: Mat.B
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.