You can achieve this using only 2 more parameters in px.line:

  • markers=True
  • color_discrete_sequence=my_plotly_continuous_sequence

The complete code would look something like this (Note the list slicing [::4] so that the colors are well spaced):

import plotly.express as px
import pandas as pd
import numpy as np

x = [1, 2, 3, 4, 5, 6]

df = pd.DataFrame(
    {
        'x': x * 3,
        'y': list(np.array(x)) + list(np.array(x) ** 2) + list(np.array(x) ** .5),
        'color': list(np.array(x) * 0) + list(np.array(x) * 0 + 1) + list(np.array(x) * 0 + 2),
    }
)

fig = px.line(
    df,
    x='x',
    y='y',
    color='color',
    color_discrete_sequence=px.colors.sequential.Plasma[::4],
    markers=True,
    template='plotly'
)
fig.show()

This produces the following output.

In case you have more lines than the colors present in the colormap, you can construct a custom colorscale so that you get one complete sequence instead of a cycling sequence:

rgb = px.colors.convert_colors_to_same_type(px.colors.sequential.RdBu)[0]

colorscale = []
n_steps = 4  # Control the number of colors in the final colorscale
for i in range(len(rgb) - 1):
    for step in np.linspace(0, 1, n_steps):
        colorscale.append(px.colors.find_intermediate_color(rgb[i], rgb[i + 1], step, colortype='rgb'))

fig = px.line(df_e, x='temperature', y='probability', color='year', color_discrete_sequence=colorscale, height=900)
fig.show()

Answer from Manuel Montoya on Stack Overflow
๐ŸŒ
Plotly
plotly.com โ€บ python โ€บ builtin-colorscales
Built-in continuous color scales in Python
A collection of predefined sequential colorscales is provided in the plotly.colors.sequential module. Sequential color scales are appropriate for most continuous data, but in some cases it can be helpful to use a diverging or cyclical color scale (see below).
๐ŸŒ
Plotly
plotly.com โ€บ python โ€บ colorscales
Continuous color scales and color bars in Python
Color scale defaults depend on the layout.colorscales attributes of the active template, and can be explicitly specified using the color_continuous_scale argument for many Plotly Express functions or the colorscale argument in various graph_objects such as layout.coloraxis or marker.colorscale in go.Scatter traces or colorscale in go.Heatmap traces.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ built-in-continuous-color-scales-in-python-plotly
Built-in Continuous Color Scales in Python Plotly - GeeksforGeeks
July 23, 2025 - Plotly has a wide variety of built-in continuous color scales that can be referenced in Python code when specifying the arguments, either by name or by reference.
๐ŸŒ
Plotly
plotly.com โ€บ r โ€บ builtin-colorscales
Built-in continuous color scales in R
A reference for the built-in named continuous (sequential, diverging and cyclical) color scales in Plotly.
๐ŸŒ
Plotly
community.plotly.com โ€บ ๐Ÿ“Š plotly python
Continuous color scale for scatter traces added individually - ๐Ÿ“Š Plotly Python - Plotly Community Forum
June 16, 2023 - I want them to have a color based on value from numerical list (normalised_PDs), as in continuous color scale. I failed, even though I think it must be very simple. Could you please help me spot the problem here? import plotly.express as px PDs = [float(x) for x in"29.7498790938959 29.7498790938959 ...
๐ŸŒ
Plotly
plotly.com โ€บ python-api-reference โ€บ generated โ€บ plotly.colors.html
plotly.colors package โ€” 7.1.0 documentation
The color scales in this module are mostly meant to be passed in as the color_continuous_scale argument to various functions, and to be used with the color_continuous_midpoint argument. ... template (str or dict or plotly.graph_objects.layout.Template instance) โ€“ The figure template name ...
Top answer
1 of 3
5

You can achieve this using only 2 more parameters in px.line:

  • markers=True
  • color_discrete_sequence=my_plotly_continuous_sequence

The complete code would look something like this (Note the list slicing [::4] so that the colors are well spaced):

import plotly.express as px
import pandas as pd
import numpy as np

x = [1, 2, 3, 4, 5, 6]

df = pd.DataFrame(
    {
        'x': x * 3,
        'y': list(np.array(x)) + list(np.array(x) ** 2) + list(np.array(x) ** .5),
        'color': list(np.array(x) * 0) + list(np.array(x) * 0 + 1) + list(np.array(x) * 0 + 2),
    }
)

fig = px.line(
    df,
    x='x',
    y='y',
    color='color',
    color_discrete_sequence=px.colors.sequential.Plasma[::4],
    markers=True,
    template='plotly'
)
fig.show()

This produces the following output.

In case you have more lines than the colors present in the colormap, you can construct a custom colorscale so that you get one complete sequence instead of a cycling sequence:

rgb = px.colors.convert_colors_to_same_type(px.colors.sequential.RdBu)[0]

colorscale = []
n_steps = 4  # Control the number of colors in the final colorscale
for i in range(len(rgb) - 1):
    for step in np.linspace(0, 1, n_steps):
        colorscale.append(px.colors.find_intermediate_color(rgb[i], rgb[i + 1], step, colortype='rgb'))

fig = px.line(df_e, x='temperature', y='probability', color='year', color_discrete_sequence=colorscale, height=900)
fig.show()

2 of 3
4

I am not sure this is possible using only plotly.express. If you use px.line, then you can pass the argument markers=True as described in this answer, but from the px.line documentation it doesn't look like continuous color scales are supported.

UPDATED ANSWER: in order to have both a legend that groups both the lines and markers together, it's probably simpest to use go.Scatter with the argument mode='lines+markers'. You'll need to add the traces one at a time (by plotting each unique color portion of the data one at a time) in order to be able to control each line+marker group from the legend.

When plotting these traces, you will need some functions to retrieve the colors of the lines from the continuous color scale because go.Scatter won't know what color your lines are supposed to be unless you specify them - thankfully that has been answered here.

Also you won't be able to generate a colorbar adding the markers one color at a time, so to add a colorbar, you can plot all of the markers at once using go.Scatter, but use the argument marker=dict(size=0, color="rgba(0,0,0,0)", colorscale='Plasma', colorbar=dict(thickness=20)) to display a colorbar, but ensure that these duplicate markers are not visible.

Putting all of this together:

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

x = [1,2,3,4,5,6]

df = pd.DataFrame(
    {
        'x': x*3,
        'y': list(np.array(x)) + list(np.array(x)**2) + list(np.array(x)**.5),
        'color': list(np.array(x)*0) + list(np.array(x)*0+1) + list(np.array(x)*0+2),
    }
)

# This function allows you to retrieve colors from a continuous color scale
# by providing the name of the color scale, and the normalized location between 0 and 1
# Reference: https://stackoverflow.com/questions/62710057/access-color-from-plotly-color-scale

def get_color(colorscale_name, loc):
    from _plotly_utils.basevalidators import ColorscaleValidator
    # first parameter: Name of the property being validated
    # second parameter: a string, doesn't really matter in our use case
    cv = ColorscaleValidator("colorscale", "")
    # colorscale will be a list of lists: [[loc1, "rgb1"], [loc2, "rgb2"], ...] 
    colorscale = cv.validate_coerce(colorscale_name)
    
    if hasattr(loc, "__iter__"):
        return [get_continuous_color(colorscale, x) for x in loc]
    return get_continuous_color(colorscale, loc)
        

# Identical to Adam's answer
import plotly.colors
from PIL import ImageColor

def get_continuous_color(colorscale, intermed):
    """
    Plotly continuous colorscales assign colors to the range [0, 1]. This function computes the intermediate
    color for any value in that range.

    Plotly doesn't make the colorscales directly accessible in a common format.
    Some are ready to use:
    
        colorscale = plotly.colors.PLOTLY_SCALES["Greens"]

    Others are just swatches that need to be constructed into a colorscale:

        viridis_colors, scale = plotly.colors.convert_colors_to_same_type(plotly.colors.sequential.Viridis)
        colorscale = plotly.colors.make_colorscale(viridis_colors, scale=scale)

    :param colorscale: A plotly continuous colorscale defined with RGB string colors.
    :param intermed: value in the range [0, 1]
    :return: color in rgb string format
    :rtype: str
    """
    if len(colorscale) < 1:
        raise ValueError("colorscale must have at least one color")

    hex_to_rgb = lambda c: "rgb" + str(ImageColor.getcolor(c, "RGB"))

    if intermed <= 0 or len(colorscale) == 1:
        c = colorscale[0][1]
        return c if c[0] != "#" else hex_to_rgb(c)
    if intermed >= 1:
        c = colorscale[-1][1]
        return c if c[0] != "#" else hex_to_rgb(c)

    for cutoff, color in colorscale:
        if intermed > cutoff:
            low_cutoff, low_color = cutoff, color
        else:
            high_cutoff, high_color = cutoff, color
            break

    if (low_color[0] == "#") or (high_color[0] == "#"):
        # some color scale names (such as cividis) returns:
        # [[loc1, "hex1"], [loc2, "hex2"], ...]
        low_color = hex_to_rgb(low_color)
        high_color = hex_to_rgb(high_color)

    return plotly.colors.find_intermediate_color(
        lowcolor=low_color,
        highcolor=high_color,
        intermed=((intermed - low_cutoff) / (high_cutoff - low_cutoff)),
        colortype="rgb",
    )

fig = go.Figure()

## add the lines+markers
for color_val in df.color.unique():
    color_val_normalized = (color_val - min(df.color)) / (max(df.color) - min(df.color))
    # print(f"color_val={color_val}, color_val_normalized={color_val_normalized}")
    df_subset = df[df['color'] == color_val]
    fig.add_trace(go.Scatter(
        x=df_subset['x'],
        y=df_subset['y'],
        mode='lines+markers',
        marker=dict(color=get_color('Plasma', color_val_normalized)),
        name=f"line+marker {color_val}",
        legendgroup=f"line+marker {color_val}"
    ))

## add invisible markers to display the colorbar without displaying the markers
fig.add_trace(go.Scatter(
    x=df['x'],
    y=df['y'],
    mode='markers',
    marker=dict(
        size=0, 
        color="rgba(0,0,0,0)", 
        colorscale='Plasma', 
        cmin=min(df.color),
        cmax=max(df.color),
        colorbar=dict(thickness=40)
    ),
    showlegend=False
))

fig.update_layout(
    legend=dict(
    yanchor="top",
    y=0.99,
    xanchor="left",
    x=0.01),
    yaxis_range=[min(df.y)-2,max(df.y)+2]
)

fig.show()

๐ŸŒ
GitHub
github.com โ€บ plotly โ€บ plotly.py โ€บ blob โ€บ main โ€บ doc โ€บ python โ€บ builtin-colorscales.md
plotly.py/doc/python/builtin-colorscales.md at main ยท plotly/plotly.py
Many Plotly Express functions accept a color_continuous_scale argument and many trace types have a colorscale attribute in their schema. Plotly comes with a large number of built-in continuous color scales, which can be referred to in Python code when setting the above arguments, either by name in a case-insensitive string e.g.
Author: plotly
๐ŸŒ
Plotly
plotly.com โ€บ python โ€บ discrete-color
Discrete colors in Python
This works because just like in px.colors.qualitative, all built-in continuous color scales are stored as lists of CSS colors: ... ['#0d0887', '#46039f', '#7201a8', '#9c179e', '#bd3786', '#d8576b', '#ed7953', '#fb9f3a', '#fdca26', '#f0f921'] Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
Find elsewhere
๐ŸŒ
Plotly
community.plotly.com โ€บ ๐Ÿ“Š plotly python
Continuous color scale with distinct colors for under/oversaturated pixels - ๐Ÿ“Š Plotly Python - Plotly Community Forum
March 11, 2023 - I would like to visualise under/oversatured pixels with continuous color scale (e.g. pixels with value 0 to be blue, pixels with value 255 to be red, the rest in gray). Is it possible? There are LUTs for this in ImageJ bโ€ฆ
๐ŸŒ
Plotly
plotly.com โ€บ fsharp โ€บ logarithmic-color-scale
Continuous Color Scales and Color Bars | Fsharp | Plotly
let z=[| [|10.0; 10.625; 12.5; 15.625; 20.0;|]; [|5.625; 6.25; 8.125; 11.25; 15.625;|]; [|2.5; 3.125; 5.0; 8.125; 12.5;|]; [|0.625; 1.25; 3.125; 6.25; 10.625;|]; [|0.0; 0.625; 2.5; 5.625; 10.0|]|] //let customColorscale = StyleParam.Colorscale.Custom [(0.0,"#A6CEE3");(1.0,"#E31A1C")] let customColorscale = StyleParam.Colorscale.Custom [(0.0,"rgb(166,206,227)");(0.25,"rgb(31,120,180)");(0.45,"rgb(178,223,138)"); (0.65,"rgb(51,160,44)");(0.85,"rgb(251,154,153)"); (1.0,"rgb(227,26,28)");] let contour = Chart.Contour(z,Colorscale=customColorscale) |> Chart.withSize(600.,600.) ... open FSharp.Data type jsondata = JsonProvider<"https://raw.githubusercontent.com/plotly/datasets/master/custom_heatmap_colorscale.json"> let data = jsondata.Load("https://raw.githubusercontent.com/plotly/datasets/master/custom_heatmap_colorscale.json")
๐ŸŒ
Naomi Aro
naomiaro.hashnode.dev โ€บ how-to-create-custom-continuous-and-discrete-colorscales-with-plotlyjs
How to create custom continuous and discrete colorscales with Plotly.js
September 9, 2024 - We'll have to normalise the last nine entries in the legend to achieve this scale. Starting with a continuous colour scale, we'll want to create equal steps to normalise our colours between 0 and 1.
๐ŸŒ
Plotly
plotly.com โ€บ ggplot2 โ€บ colorscales
Continuous color scales and color bars in ggplot2
library(plotly) library(ggplot2) df <- data.frame( x = runif(100), y = runif(100), z1 = rnorm(100), z2 = abs(rnorm(100)) ) p <- ggplot(df, aes(x, y)) + geom_point(aes(colour = z1)) + scale_colour_gradientn(colours = terrain.colors(10)) ggplotly(p)
Top answer
1 of 1
2

You should add new plots to the first one, I have a small number of samples to plot, you can play with other configurations as you want:

import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd
from openpyxl import load_workbook
import numpy as np
import pandas as pd
from io import StringIO

import numpy as np; 
np.random.seed(0)
import seaborn as sns;




data = '''
x   y   Base_TT
14.1315559  55.75811117 1.871884861
14.66228957 57.02751992 1.599971112
14.49407157 56.06563489 1.307165278
13.21996788 55.4786748  1.411554445
14.00501286 55.72120854 1.968138334
12.73736102 56.71097302 1.309849028
14.56668525 56.74872925 1.719116945
13.24138764 56.41359089 2.000620417
14.94308088 56.54283706 1.668724723
14.5744739  56.05695327 1.266861528
'''

df_centroid_Coord = pd.read_csv(StringIO(data), delim_whitespace=True)


data = '''
ID "Ambulance station name" Longtitude Latitude
0 1 AImhult 14.128734 56.547992
1 2 Angelhdm 12.870739 56.242114
2 3 Alvesta 14.549503 56.920740
3 4 "Ostra Ljungby" 13.057450 56.188099
4 5 Broby 14.080958 56.254481
5 6 Bromรถlla 14.466869 56.072272
6 7 Fรถrslรกv 12.814913 56.350098
7 9 Hasslehdm 13.778234 56.161536
8 10 Haganas 12.556995 56.206016
9 11 Hรถrby 13.643265 55.849811
10 12 "Halmstad.Vaster" 12.819960 56.674306 
'''

df_station = pd.read_csv(StringIO(data), delim_whitespace=True) 
df_station.rename(columns={'Longtitude':'x', 'Latitude':'y'}, inplace=True)
df_centroid_Coord['Ambulance_Treatment_Time'] = df_centroid_Coord ['Base_TT']

fig = px.scatter(df_centroid_Coord, x="x", y="y", 
                 title="Southern Region Centroids", 
                 color='Ambulance_Treatment_Time', 
                 log_x=True,
                 size_max=60, 
                 color_continuous_scale='Reds',
                 range_color=(0.5,2),
                 )

fig.update_traces(marker={'size': 4, 'symbol': 1})
fig.add_trace(go.Scatter(x=df_station['x'],
                         y=df_station['y'],
                         mode='markers+text',
                         text=df_station['Ambulance station name'],
                         textposition='top center',
                         showlegend=True,
                         marker=dict(
                             size=8,
                             symbol=2,
                             color='black'
                         )
                        )
             )



fig.show()

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-plotly-how-to-set-up-a-color-palette
Python Plotly - How to set up a color palette? - GeeksforGeeks
July 23, 2025 - px. scatter() method is used to plot a scatterplot of continuous data. We explicitly make a color palette by making a list of the colors. The list is passed to the colour_continuous_scale parameter of the px.scatter() method as we're working ...
๐ŸŒ
Plotly
plotly.com โ€บ python-api-reference โ€บ generated โ€บ plotly.express.colors.html
plotly.express.colors package โ€” 7.1.0 documentation
template (str or dict or plotly.graph_objects.layout.Template instance) โ€“ The figure template name or definition. ... fig โ€“ A Figure object. This figure demonstrates the color scales and sequences in this module, as polar bar charts. ... Diverging color scales are appropriate for continuous ...
Top answer
1 of 1
1

I think the best method would be to use one trace to create the boxplot, and another trace to create a scatterplot of the points. You have more parameters you can set in a scatterplot, and you can also set the colorscale of the marker in a dictionary: by passing an array with 0 mapped to dark red, 0.5 mapped to transparent grey (opacity = 0), and 1 mapped to dark green.

Since the boxplot is categorical, and you passed the parameter name='Markers', if we set the y values of the scatterplot to 'Markers' the scatterplot of the points will be superimposed on top of the boxplot. Also, as an aside, it's a good idea to set a seed to ensure reproducibility.

import random
import numpy as np 
import plotly.graph_objects as go

np.random.seed(42)
rand = np.random.uniform(-100, 100, 100)

fig = go.Figure()
fig.add_trace(go.Box(
    x=rand,
    name='Markers',
    showlegend=True,
    jitter=0,
    pointpos=0,
    line_color='rgba(128, 128, 128, .0)',
    fillcolor='rgba(128, 128, 128, .3)',
))

## add the go.Scatter separately from go.Box so we can adjust more marker parameters
## the colorscale parameter goes from 0 to 1, but will scale with your range of -100 to 100
## the midpoint is 0.5 which can be grey (to match your boxplot) and have an opacity of 0 so it's transparent
fig.add_trace(go.Scatter(
    x=rand,
    y=['Markers']*len(rand),
    name='Markers',
    mode="markers",
    marker=dict(
        size=16,
        cmax=100,
        cmin=-100,
        color=rand,
        colorscale=[[0, 'rgba(214, 39, 40, 0.85)'],   
               [0.5, 'rgba(128, 128, 128, 0)'],  
               [1, 'rgba(6,54,21, 0.85)']],
    ),
    showlegend=False
)).data[0]
fig.update_layout(template='plotly_white')
fig.show()

๐ŸŒ
Plotly
community.plotly.com โ€บ ๐Ÿ“Š plotly python
Ploty continuous color scale in line chart - ๐Ÿ“Š Plotly Python - Plotly Community Forum
November 11, 2020 - Hi, I was experimenting with the various options available, but I couldnโ€™t manage to set continuous color scale on a single line of a line chart. Discrete colors worked fine. I would appreciate if someone could point me the right direction regarding how to use x or y (in this case year or life expectancy) or any other values to set continuous color if it is possible.
๐ŸŒ
Plotly
plotly.com โ€บ fsharp โ€บ colorscales
Continuous color scales and color bars in Fsharp
Added Kernel Extension including formatters for Plotly.NET charts. ... let z=[[0;1;2;3;4;5;6;7;8;9]] let customColorscale = StyleParam.Colorscale.Custom [(0.0,"#000000");(1.0,"#B4B4B4")] Chart.Heatmap(z,Colorscale=customColorscale) |> ...