Search code examples
pythonplotplotlybar-chart

Plotting bars with 5 min interval and adding a line


I am trying to plot closing price with positive and negative sentiment. I was able to plot it as the picture below; however, the colors are not showing properly for the bar chart. Any ideas how to change them?

from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig2 = make_subplots(specs=[[{"secondary_y": True}]])
fig2.add_trace(go.Scatter(x=data.index,y=data['close'],name='Price'),secondary_y=False)
fig2.add_trace(go.Bar(x=data.index,y=data['pos'],name='Positive'),secondary_y=True)
fig2.add_trace(go.Bar(x=data.index,y=data['neg'],name='Negative'),secondary_y=True)

fig2.show()

Graph


Solution

    • have implied you dataframe structure from your code and used plotly finance sample data set as starting point
    • two things to look at wrt to layout
      1. make Close trace the primary trace at front
      2. review bargroup parameter and reduce bargap to zero
    from plotly.subplots import make_subplots
    import plotly.graph_objects as go
    import pandas as pd
    
    df = pd.read_csv(
        "https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv"
    )
    
    # make plotly dataset compatible with OP implied structure
    data = df.set_index(pd.date_range("1-Jan-2022", freq="5Min", periods=len(df))).rename(
        columns={"AAPL.Close": "close", "dn": "neg", "up": "pos"}
    )
    
    fig2 = make_subplots(specs=[[{"secondary_y": True}]])
    fig2.add_trace(
        go.Scatter(x=data.index, y=data["close"], name="Price"), secondary_y=False
    )
    fig2.add_trace(go.Bar(x=data.index, y=data["pos"], name="Positive"), secondary_y=True)
    fig2.add_trace(go.Bar(x=data.index, y=data["neg"], name="Negative"), secondary_y=True)
    
    
    # a few changes to make layout work better
    #  1. put close at front
    #  2. reduce "whitespace" in bars
    fig2.update_layout(
        yaxis={"overlaying": "y2"}, yaxis2={"overlaying": None}, barmode="overlay", bargap=0
    )
    

    enter image description here