Soerendip
Soerendip

Reputation: 9148

How to rotate the axis labels in plotly scatterplotmatrix?

With plotly express scattermatrix

import plotly.express as px
df = px.data.iris()
fig = px.scatter_matrix(df)
fig.show()

I would like to rotate the axis-labels (not the tick-labels) of the y-axis, which correspond to the columns in the dataframe, so that they are horizontal. Because, for longer names and more subplots the labels start overlapping pretty quickly. Is that currently doable?

enter image description here

Upvotes: 2

Views: 1942

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31166

  • axis ticks can be rotated. I cannot find any way to rotate labels
  • as a workaround, replace labels and add a key
import plotly.express as px

df = px.data.iris()
fig = px.scatter_matrix(df)

# rotate text in yaxes, if text
fig.update_layout(
    {
        f"yaxis{n+1 if n>0 else ''}": {"tickangle": 45}
        for n in range(len(fig.data[0].dimensions))
        if isinstance(fig.data[0].dimensions[n].values[0], str)
    }
)

# get labels of dimensions in splom
labels = [d.label for d in fig.data[0].dimensions]

# replace labels in splom with identifier
fig.update_traces(
    dimensions=[d.update(label=chr(ord("a")+n)) for n, d in enumerate(fig.data[0].dimensions)]
)

# add a key for labels
for n, l in enumerate(labels):
    fig.add_annotation(
        x=(n) / (len(labels)-1),
        y=1.2,
        xref="paper",
        yref="paper",
        text=f"{chr(ord('a')+n)}. {l}",
        align="center",
        showarrow=False,
    )

fig

enter image description here

Upvotes: 2

Related Questions