Skip to content

Instantly share code, notes, and snippets.

@caiotaniguchi
Last active January 18, 2022 16:19
Show Gist options
  • Save caiotaniguchi/2031c1614e6b8aa142198fe548c4b77f to your computer and use it in GitHub Desktop.
Save caiotaniguchi/2031c1614e6b8aa142198fe548c4b77f to your computer and use it in GitHub Desktop.
Plotting Lollipop Charts with Plotly
import numpy as np
import plotly.offline as pyo
import plotly.graph_objs as go
# Generate a random signal
np.random.seed(42)
random_signal = np.random.normal(size=100)
# Offset the line length by the marker size to avoid overlapping
marker_offset = 0.04
def offset_signal(signal, marker_offset):
if abs(signal) <= marker_offset:
return 0
return signal - marker_offset if signal > 0 else signal + marker_offset
data = [
go.Scatter(
x=list(range(len(random_signal))),
y=random_signal,
mode='markers',
marker=dict(color='red')
)
]
# Use the 'shapes' attribute from the layout to draw the vertical lines
layout = go.Layout(
shapes=[dict(
type='line',
xref='x',
yref='y',
x0=i,
y0=0,
x1=i,
y1=offset_signal(random_signal[i], marker_offset),
line=dict(
color='grey',
width=1
)
) for i in range(len(random_signal))],
title='Lollipop Chart'
)
# Plot the chart
fig = go.Figure(data, layout)
pyo.iplot(fig)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment