Search code examples
pythonplotly

plotly - add vline with default grid color


I would like to add a vline with default gride color. below code use lightgray as vline color, how to make it the same as the default grid color?

import plotly.graph_objects as go

def main():
    x = [1, 2, 3, 4, 5]
    y = [10, 11, 12, 11, 9]

    fig = go.Figure()

    fig.add_trace(go.Scatter(x=x, y=y, mode='lines'))
    fig.add_vline(x=2.5, line_width=.5, line_dash="solid", line_color="lightgray")

    fig.update_layout(title='demo',template="plotly_dark",xaxis_title='x', yaxis_title='y')

    fig.show()
    return


[


Solution

  • You can use fig.layout.template.layout.xaxis.linecolor to get the vertical grid lines colors and fig.layout.template.layout.yaxis.linecolor for the horizontal ones. It's usually the same color so it doesn't matter.

    But to have it, the figure must first be updated with the new theme, so update_layout must be put first. So the code would like:

    import plotly.graph_objects as go
    
    
    def main():
        x = [1, 2, 3, 4, 5]
        y = [10, 11, 12, 11, 9]
    
        fig = go.Figure()
        fig.update_layout(
            title="demo", template="plotly_dark", xaxis_title="x", yaxis_title="y"
        )
        grid_color = fig.layout.template.layout.xaxis.gridcolor
        fig.add_trace(go.Scatter(x=x, y=y, mode="lines"))
        fig.add_vline(x=2.5, line_width=0.5, line_dash="solid", line_color=grid_color)
    
    
    
        fig.show()
        return