Succint way to add line segments to plotly graph (with python/jupyter notebook)?

后端 未结 1 1500
无人及你
无人及你 2021-01-13 17:07

I want to create a lollipop plot with several horizontal line segments like this - https://python-graph-gallery.com/184-lollipop-plot-with-2-group. I\'d like to use plotly s

1条回答
  •  孤城傲影
    2021-01-13 17:41

    Plotly doesn't provide a built in vectorization for such chart, because it can be done easily by yourself, see my example based on your provided links:

    import pandas as pd
    import numpy as np
    import plotly.offline as pyo
    import plotly.graph_objs as go
    
    # Create a dataframe
    value1 = np.random.uniform(size = 20)
    value2 = value1 + np.random.uniform(size = 20) / 4
    df = pd.DataFrame({'group':list(map(chr, range(65, 85))), 'value1':value1 , 'value2':value2 })
    
    my_range=range(1,len(df.index)+1)
    
    # Add title and axis names
    data1 = go.Scatter(
            x=df['value1'],
            y=np.array(my_range),
            mode='markers',
            marker=dict(color='blue')
        )
    
    
    data2 = go.Scatter(
            x=df['value2'],
            y=np.array(my_range),
            mode='markers',
            marker=dict(color='green')
        )
    
    # Horizontal line shape
    shapes=[dict(
            type='line',
            x0 = df['value1'].loc[i],
            y0 = i + 1,
            x1 = df['value2'].loc[i],
            y1 = i + 1,
            line = dict(
                color = 'grey',
                width = 2
            )
        ) for i in range(len(df['value1']))]
    
    
    layout = go.Layout(
        shapes = shapes,
        title='Lollipop Chart'
    )
    
    # Plot the chart
    fig = go.Figure([data1, data2], layout)
    
    pyo.plot(fig)
    

    With the result I got:

    0 讨论(0)
提交回复
热议问题