0
votes

I have a simple strip plot with a categorical x-axis. I want to add a vertical line (on different y-values) for each category.

I am able to to create one vertical line throughout the plot like this:

import plotly.express as px

fig = px.strip(df, x="category", y="value")
fig.add_hline(y=191)

Result looks like this:

enter image description here

However, I am unable to plot one vertical line for each category.

Desired Output

My desired output is something like this:

enter image description here

I tried adding a shape to the layout, but it did not affect the output:

fig.update_layout(shapes=[
    dict( type= 'line',
      yref= 'paper', y0= 180, y1= 180,
      xref= 'x', x0= "cat1", x1= "cat1")])

Something like this would probably work if the x-axis is numeric. However, not sure how to specify the category here. If this is the way to go, then I am probably doing it wrong.

How would I be able to add a single horizontal line, as depcited above, with a different y-value for each category?


Data to reproduce plot:

import pandas as pd

df = pd.DataFrame(data={
    "category": ["cat1", "cat1", "cat2", "cat2"],
    "value": [150, 160, 180, 190]
})
1

1 Answers

1
votes

Add lines with shapes. There are two types of coordinate axes: x,y axis and paper-based. From your desired output, you can read and specify the x-axis as paper-based and the y-axis as the y-axis value.

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'category':['cat1','cat1','cat2','cat2'],'value':[150,160,180,190]})
fig = px.strip(df, x="category", y="value")

fig.update_layout(shapes=[dict(type='line', x0=0.2, y0=180, x1=0.3, y1=180,
                               xref='paper', yref='y',
                               line_width=3, line_color='red'),
                          dict(type='line', x0=0.7, y0=192, x1=0.8, y1=192,
                               xref='paper', yref='y',
                               line_width=3, line_color='red'),
                         ])
fig.show()

enter image description here