I have a dataset that I would like to visualize using a line plot sorted by date. Each line in the plot represents a distinct variable, and I intend to assign a gradient of colors to these lines.
Below, is a sample code snippet (ref here):
import pandas as pd
import plotly.express as px
data = {'date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02','2024-01-02', '2024-01-03','2024-01-03'],
'color': [1, 3, 2, 3, 1, 3, 2],
'sample': [0.5, 0.2, 0.8, 0.7, 0.4, 0.9, 0.3]}
df1 = pd.DataFrame(data)
myscale = px.colors.sample_colorscale(colorscale=px.colors.sequential.Blues,
samplepoints=len(df1['color'].unique()),
low=0.0, high=1.0, colortype="rgb",
)
px.line(df1, x="date", y="sample", markers=True, color='color', color_discrete_sequence=myscale,).show()
As you can see in the provided visualization, the colors assigned to the lines follow a cyclic pattern. However, since my variables are ordinal, I would like to customize the color gradient such that each line corresponds to a distinct shade of blue, with:
Desired output
the first line being light blue for (color = 1)
,
the second line slightly darker for (color = 2)
,
and the third line being the darkest for (color = 3)
.
Current output
the first line being light blue for (color = 1)
,
the second line slightly darker for (color = **3**)
,
and the third line being the darkest for (color = **2**)
.
Are you looking for that ? :
import pandas as pd
import plotly.express as px
data = {
'date': ['2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02', '2024-01-02', '2024-01-03', '2024-01-03'],
'color': [1, 3, 2, 3, 1, 3, 2],
'sample': [0.5, 0.2, 0.8, 0.7, 0.4, 0.9, 0.3]
}
df1 = pd.DataFrame(data)
# Defining a custom color scale
color_scale = {
1: 'lightblue', # Light blue for color = 1
2: 'deepskyblue', # Slightly darker for color = 2
3: 'royalblue' # Darkest for color = 3
}
fig = px.line(df1, x="date", y="sample", markers=True,
color='color',
color_discrete_map=color_scale # Using the custom color scale
)
fig.show()