简体   繁体   中英

Plotly: How to set a unique color for each series in a scatter plot?

I have a dataframe in pandas with stock tickers as the index and 2 columns 'Active Weights' and 'Weights'. I can make a scatter plot using the code below, but I want to use a unique color for each ticker. How can I do this?

    scatter = [go.Scatter(x = df['Active Weight'], y = df['Weight'],
    mode='markers', text=df.index)]

    plotly.offline.iplot(scatter)

I may be missing something here, but by the sound of it, you're really just looking for a scatter plot such as this:

在此处输入图片说明

The code below is set up to follow the default color cycle of plotly. But you can change that to any other colorscheme from plotly express like px.colors.qualitative.Plotly . Or just make your own like ['black', 'yellow'].

Complete code:

# imports
import plotly.express as px
import plotly.graph_objs as go
import pandas as pd
import numpy as np

# data 1
np.random.seed(123)
frame_rows = 40
frame_columns = ['Active Weight', 'Weight']
df= pd.DataFrame(np.random.uniform(-10,10,size=(frame_rows, len(frame_columns))),
                  index=pd.date_range('1/1/2020', periods=frame_rows),
                    columns=frame_columns)
df=df.cumsum()+100
df.iloc[0]=100

# color settings
#colors=px.colors.qualitative.plotly 
#colors=px.colors.qualitative.Dark24_r 
colors = ['black', 'yellow']

# plotly figure
fig = go.Figure()
for i, col in enumerate(df):
    fig.add_traces(go.Scatter(x=df.index, y = df[col].values,
                              mode = 'markers',
                              name = col,
                              marker=dict(color=colors[i])))

fig.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM