'Python plotly - Apply log scale on a specific axis by index

Can you please show a solution how to set logarithmic scale for a specific y axis by index in python plotly (without using plotly express)?

This document shows, how to apply log scaling for all axes:

fig.update_xaxes(type="log")

You can even apply log scaling for only a specific graph:

fig.layout.yaxis2.plot_type = "log"

As you can see in the example, unfortunately number 2 is now hard coded. I'm seeking a solution similar to this:

apply_log_on = 2
fig.layout.yaxis[apply_log_on].plot_type = "log"

It would be even better if I could apply it on fig.add_trace:

fig = make_subplots(...)
fig.add_trace(
    go.Scatter(
        x=...
        y=...
        ...
        yaxis=dict(plot_type="log"),   # Does not work (also tried with type instead of plot_type
    )
)

One possible solution could be to execute the code as a string (for example with exec):

y = 2
exec(f"fig.layout.yaxis{y}.type = 'log'")

Is there a cleaner solution?



Solution 1:[1]

The fig.layout data is in dictionary format, so we will search for xaixs and yaxis as its key values. When a match is found, change the axis tick format type to Log format. This is a tried and tested solution for scatter plots, so you may need to adjust the search for other graphs.

import plotly.graph_objects as go
import plotly.express as px
df = px.data.gapminder().query("year == 2007")

fig = go.Figure()

fig.add_trace(go.Scatter(mode="markers", x=df["gdpPercap"], y=df["lifeExp"] ))

for k in fig.layout:
    if k[:5] == 'xaxis' or k[:5] ==  'yaxis':
        print(k)
        fig.layout[k]['type'] = 'log'

        
# fig.update_xaxes(type="log", range=[0,5]) # log range: 10^0=1, 10^5=100000
# fig.update_yaxes(range=[0,100]) # linear range

fig.show()

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1