Plotly Flashcards
What’s the general syntax for creating a Plotly scatterplot? (Graph Objects, not Express)
fig = go.Figure()
trace = go.Scatter(x=…, y=…, mode=’markers’, marker={}, showlegend=True, name=’my dotz’, custom_data=…, hovertemplate=…)
fig.add_trace(trace)
fig.update_layout()
fig.show()
On hover, how do you make it show “spike lines” that extend down to the X and Y axes?
fig.update_layout(xaxis={‘showspikes’:True})
How do you shift the origin point of the X or Y axis (e.g., have it show up at 0 instead of all the way at the bottom/left of the graph)?
You don’t. That’s a separate thing called “zero line”:
fig.update_layout(xaxis={‘zeroline’:True, ‘zerolinecolor’:’black’, ‘zerolinewidth’:3}
How to customize hover?
- Create a 2D numpy array of all the extra vars needed for hover info (not already specified as other arguments like x or y).
custom_data = dfp[[‘stock’, ‘basis’, ‘years_held_real’]].values # MUST be a numpy array - not a Series, not a list
- Create a hovertemplate: a long string with var names like so: %{varname} (don’t forget the % sign). E.g.:
hover_template = ‘<br></br>‘.join([’%{customdata[0]}’, ‘%{x} guru’, ‘<b>%{y}</b> follower’, ‘$%{customdata[1]:,}m invested’, ‘%{customdata[2]}<extra></extra>’ ])
- Can use HTML tags like <br></br> and <b></b>
- <extra></extra>is how to get rid of the pesky default “Trace0” to the right of the hover rectangle
- go.Scatter(x=…, y=…, customdata=custom_data, hovertemplate=hover_template)
How to toggle multiple traces (e.g., 2 lines or 3 sets of scatter points) with one legend item?
Have them be different names in the legend but the same “legendgroup”, and have all but one of them as showlegend=False:
trace1 = go.Scatter(…, name=’trace1’, legendgroup=0)
trace2 = go.Scatter(…, name=’trace2’, legendgroup=0, showlegend=False)