Search code examples
pythonchartsplotlysubplotfacet

Adding dynamic shapes to plotly facet charts - Python


I need to make faceted lollipop charts in plotly, which should consist of a scatter plot with line shapes added:

import plotly.express as px

fig = px.scatter(
        x=df['x_variable'],
        y=df['y_variable'],
        facet_col = df['facet_variable'])

for i in range(0,len(df)):
    fig.add_shape(
        type="line",
        x0=df['x_variable'][i],
        y0=0,
        x1=df['x_variable'][i],
        y1=df['y_variable'][i])

The problem is that all the shapes get printed on the first facet. Is there a way to loop through each facet and add the correct shapes? Note that the above loop goes through each observation in the subplot (facet) and draws a line between the 0 on the y-axis and the marker.

I know how to add static shapes (e.g. rectangles) to faceted charts, but struggling with dynamic shapes such as the above. Any help would be much appreciated!


Solution

  • I think you may try to create the subplots with make_subplot instead of facet_col. See the examples in the section "Synchronizing axes in subplots with matches": Facet and Trellis Plots in Python and in this question .