add color to markers with plotly python

Question:

How can I change marker’s color based on the z array? The colors can be anything but need differ if value of z is differ! i understand that plotly express can do it, but i need to use plotly graph objects

I try to add a color=z entry but it report error!

import numpy as np
import plotly.graph_objects as go

def plot(x,y,z):
    fig = go.Figure()    
    trace1 = go.Scatter(
        x=x, y=y,
        z = z, #<- error line
        mode='markers',
        name='markers')
    
    fig.add_traces([trace1])
    
    tickvals = [0,np.pi/2,np.pi,np.pi*3/2,2*np.pi]
    ticktext = ["0","$\frac{pi}{2}$","$pi$","$\frac{3pi}{4}$","$2pi$"]
    layout = dict(
        title="demo",
        xaxis_title="X",
        yaxis_title="Y",
        title_x=0.5,   
        margin=dict(l=10,t=20,r=10,b=40),
        height=300,
        xaxis=dict(
            side='bottom',
            linecolor='black',
            tickangle=0,
            tickvals = tickvals,
            ticktext=ticktext,
            #tickmode='auto',
            ticks='outside',
            ticklen=7,
            tickwidth=1,
            tickcolor='black',
            tickson="labels",
            title=dict(standoff=5),
            showticklabels=True,
        ),
        yaxis=dict(
            showgrid=True,
            zeroline=True,
            zerolinewidth=.5,
            zerolinecolor='black',
            showline=True,
            linecolor='black',            
            showticklabels=True,
        )
    )

    fig.update_traces(
        marker_size=14,
    )    
    fig.update_layout(layout)
    
    save_fig(fig,"/vagrant/work/demo.png")
    fig.show()
    return

n = 20
x = np.linspace(0.0, 2*np.pi, n)
y = np.sin(x)
z = np.random.randint(0,100,size=n)

plot(x,y,z)
Asked By: lucky1928

||

Answers:

In this case, the desired graph can be created by specifying the z value in the marker color settings.

def plot(x,y,z):
    fig = go.Figure()    
    trace1 = go.Scatter(
        x=x, y=y,
        marker=dict(
            color = z),
        mode='markers',
        name='markers')
...

n = 20
x = np.linspace(0.0, 2*np.pi, n)
y = np.sin(x)
z = np.random.randint(0,100,size=n)

plot(x,y,z)

enter image description here

Answered By: r-beginners
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.