geds133
geds133

Reputation: 1485

How to add a line to a plotly express bar chart

I am trying to add a very simple line across a bar chart in plotly and am struggling to to this. My dataframe contains one column with bins and the other with returnsdata and can be copied here:

{'bins': {0: '(-23.077, 25.877]', 1: '(25.877, 34.666]', 2: '(34.666, 42.552]', 3: '(42.552, 46.044]', 4: '(46.044, 49.302]', 5: '(49.302, 52.746]', 6: '(52.746, 57.075]', 7: '(57.075, 62.349]', 8: '(62.349, 69.171]', 9: '(69.171, 90.975]'}, 'returns': {0: 0.39754, 1: 0.6817, 2: -0.1918399999999998, 3: -0.44406, 4: -0.6611199999999998, 5: -0.0742857142857142, 6: 0.25304, 7: 0.4166, 8: 0.97648, 9: 0.0539999999999999}}

I have created a plotly bar chart from this using the following code:

fig = px.bar(dfs, x='bins', y='returns')
fig.show()

enter image description here

I want to add a constant line across the bar chart that represents a benchmark score and have looked at this: Plotly: How to add trendline to a bar chart?

The methods seem to be depreciated and I can't seem to find any way to do this. The benchmark list is this:

[0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858]

I want it to look this this (the line is suppose to be straight, apologies for the terrible paint job edit)

Would anyone know how to do this?

enter image description here

Upvotes: 5

Views: 13594

Answers (2)

vestland
vestland

Reputation: 61084

I would simply use:

fig.add_traces(go.Scatter(x= dfs.bins, y=dfs.benchmark, mode = 'lines'))

Plot

enter image description here

Complete code:

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
dfs = pd.DataFrame({'bins': {0: '(-23.077, 25.877]', 1: '(25.877, 34.666]', 2: '(34.666, 42.552]', 3: '(42.552, 46.044]', 4: '(46.044, 49.302]', 5: '(49.302, 52.746]', 6: '(52.746, 57.075]', 7: '(57.075, 62.349]', 8: '(62.349, 69.171]', 9: '(69.171, 90.975]'}, 'returns': {0: 0.39754, 1: 0.6817, 2: -0.1918399999999998, 3: -0.44406, 4: -0.6611199999999998, 5: -0.0742857142857142, 6: 0.25304, 7: 0.4166, 8: 0.97648, 9: 0.0539999999999999}})
dfs['benchmark'] = [0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858, 0.14080542857142858]

fig = px.bar(dfs, x='bins', y='returns')
fig.add_traces(go.Scatter(x= dfs.bins, y=dfs.benchmark, mode = 'lines'))
fig.show()

Upvotes: 1

Derek O
Derek O

Reputation: 19565

You can use the Plotly's horizontal and vertical shapes to add a horizontal line:

fig.add_hline(y=0.14080542857142858)

Upvotes: 5

Related Questions