Search code examples
pythonplotlyplotly-python

Plotly - How to set width to specific line?


I'm trying to draw a graph with plotly libraries and I want to set a specific width of each line.

This is my code.


x_link = [125, 257, None, 125, 787, None]
y_link = [383, 588, None, 383, 212, None]
z_link = [65, 85, None, 65, 526, None]

link_size = [3,6]

trace1= go.Scatter3d(
                x = x_link, 
                y = y_link,
                z = z_link,
                line=dict(
                    color='#0061ff',
                    width=link_size
                )
)

But it raises this error.

Invalid value of type 'builtins.list' received for the 'width' property of scatter3d.line Received value: [3, 6]

The 'width' property is a number and may be specified as: - An int or float in the interval [0, inf]

So, is there a way to set the specific width of each line?

Thank you.


Solution

  • You're going to have to add individual traces for your dataset to do this since line=dict(width) only takes one single argument and not an array of some sort. And that can be a lot of work for larger datasets. But If you change your dataset from lists to a list of lists, you can take even more datapoints into account. So with a little data manipulation you can turn this:

    x_link = [125, 257, None, 125, 787, None]
    y_link = [383, 588, None, 383, 212, None]
    z_link = [65, 85, None, 65, 526, None]
    

    into this:

    x_link = [[125, 257, None], [125, 787, None]]
    y_link = [[383, 588, None], [383, 212, None]]
    z_link = [[65, 85, None], [65, 526, None]]
    

    and run this code:

    import plotly.graph_objects as go
    from plotly.offline import init_notebook_mode, iplot
    
    x_link = [[125, 257, None], [125, 787, None]]
    y_link = [[383, 588, None], [383, 212, None]]
    z_link = [[65, 85, None], [65, 526, None]]
    
    # figure formatting
    colors=['red', 'green']
    link_size = [2,12]
    
    # make multiple traces
    traces={}
    for i in range(0, len(x_link)):
        traces['trace_' + str(i)]=go.Scatter3d(x = x_link[i], 
                                               y = y_link[i],
                                               z = z_link[i],
                                               line=dict(
                                                    color=colors[i],
                                                    width=link_size[i]))
    data=list(traces.values())
    
    # build and plot figure
    fig=go.Figure(data)
    fig.show()
    

    to get this plot:

    enter image description here