Skip to content

Instantly share code, notes, and snippets.

@powergold1
Last active March 3, 2024 02:55
Show Gist options
  • Save powergold1/99d178db5dd3010f162a30e54e6b479f to your computer and use it in GitHub Desktop.
Save powergold1/99d178db5dd3010f162a30e54e6b479f to your computer and use it in GitHub Desktop.
Symlog plot in plotly (python)
# Plotly does currently not have a symlog plot built-in, but you can do the symlog
# transformation yourself, plot the data on a linear scale, and adjust the
# ticks and hovertext.
# This script below creates a plot with a symlogged y-axis similar to the second
# plot in the matplotlib demo.
# https://matplotlib.org/stable/gallery/scales/symlog_demo.html
import numpy as np
import plotly.graph_objects as go
dt = 0.01
y = np.arange(-50.0, 50.0, dt)
x = np.arange(0, 100.0, dt)
y_orig = y
y = np.where((y < -1) | (y > 1), np.sign(y) * (1 + np.log10(np.abs(y))), y)
miny = int(np.floor(np.nanmin(y)))
maxy = int(np.ceil(np.nanmax(y)))
tickvals = list(range(miny, maxy+1))
exponents = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹']
def getticktext(i):
if i == 0:
return '0'
a = abs(i)
if a == 1:
return str(i)
num = '-10' if i < 0 else '10'
if a > 2:
num = num + ''.join(exponents[int(i)] for i in str(a-1))
return num
ticktext = [getticktext(i) for i in tickvals]
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=x,
y=y,
customdata=y_orig,
hovertemplate='(%{x}, %{customdata})',
)
)
fig.update_layout(
title_text='symlog',
yaxis={
'tickvals': tickvals,
'ticktext': ticktext,
}
)
fig.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment