Home > Net >  How to add a line to a plotly express bar chart
How to add a line to a plotly express bar chart

Time:12-01

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: enter image description here

CodePudding user response:

You can use the Plotly's 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()
  • Related