Search code examples
pythonplotlydata-visualizationplotly-dashplotly-python

Plotly: How to change legend item shape from line to box or circle in a line chart?


I want to change the item shape of my legend from line to any other appealing shape like a box or a circle. Below is my chart. You can see the legend item is showing a colored line. It is not very appealing.

How do I change the shape of the legend item without changing the chart type?

my plot-line legend

Below is the example of a desired item shape for my legend.

desired-plot


Solution

  • Your best option to hopefully make your legend symbols a bit more visually appealing without messing up the figure traces as well seems to be:

    fig.layout.legend.itemsizing = 'constant'
    

    Which will give you the following legend with items that at least look a bit more like a box or rectangle instead of a line:

    enter image description here

    Instead of this:

    enter image description here

    Some details:

    The shape of the legend by default reflects the shape of your trace. That also goes for size and shape of a marker symbol. So if you build a plot like this:

    enter image description here

    Then you can always change the way the legend looks through:

    fig.data[0].mode = 'markers+lines'
    fig.data[0].marker.symbol = 'diamond'
    fig.data[0].marker.size = 12
    

    But the problem is that this goes for the figure traces as well as you can see here:

    enter image description here

    And I've made a few attempts on setting a marker symbol and then removing the marker for the traces to hopefully retain the marker in the legend. But that doesn't work. And I think we're all better off for it. So that leaves you with my initial suggestion.

    Complete code:

    # imports
    import pandas as pd
    import plotly.express as px
    
    # data
    df = px.data.stocks()
    df = df.drop(['AMZN', 'AAPL', 'MSFT', 'FB'], axis = 1)
    colors = px.colors.qualitative.T10
    
    # plotly
    fig = px.line(df, 
                     x = 'date',
                     y = [c for c in df.columns if c != 'date'],
                     template = 'plotly_dark',
                     color_discrete_sequence = colors,
                     title = 'Stocks', 
                 )
    fig.data[0].mode = 'markers+lines'
    fig.data[0].marker.symbol = 'diamond'
    fig.data[0].marker.size = 12
    
    fig.layout.legend.itemsizing = 'constant'
    fig.show()