如何使用 Plotly 创建具有 n 种颜色的离散颜色图

How to create discrete colormap with n colors using Plotly

我想为 Python 中的 plotly express plot 创建一个 n 颜色的颜色图,它应该从一种颜色淡入另一种颜色。 所有默认颜色图只有 10 个离散值,但我正在寻找具有 n > 10 个离散值的颜色图。

>>> px.colors.sequential.Plasma_r

['#f0f921',
 '#fdca26',
 '#fb9f3a',
 '#ed7953',
 '#d8576b',
 '#bd3786',
 '#9c179e',
 '#7201a8',
 '#46039f',
 '#0d0887']

有没有办法把一张连续的地图分割成n份?

如果您不介意,rgb colors, then n_colors 是一种选择。这是 'rgb(0, 0, 0)''rgb(255, 255, 255)' 之间灰度中 15 种颜色的示例:

 n_colors('rgb(0, 0, 0)', 'rgb(255, 255, 255)', 15, colortype='rgb')

下面是蓝色 'rgb(0, 0, 255)' 和红色 'rgb(255, 0, 0)' 之间的 25 种颜色的示例:

n_colors('rgb(0, 0, 255)', 'rgb(255, 0, 0)', 25, colortype = 'rgb')

完整代码:

import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import datetime
from plotly.colors import n_colors

pd.set_option('display.max_rows', None)
pd.options.plotting.backend = "plotly"


# greys15 = n_colors('rgb(0, 0, 0)', 'rgb(255, 255, 255)', 15, colortype='rgb')
redVSblue = n_colors('rgb(0, 0, 255)', 'rgb(255, 0, 0)', 25, colortype = 'rgb')

fig = go.Figure()

# for i, c in enumerate(greys15):
for i, c in enumerate(redVSblue):
    fig.add_bar(x=[i], y = [i+1], marker_color = c, showlegend = False)
f = fig.full_figure_for_development(warn=False)
fig.show()

类似于已接受的响应,但能够使用可在 this tutorial

中找到的内置名称

colors 包含 n_colors 的列表,可以视为 list

import plotly.express as px

n_colors = 25
colors = px.colors.sample_colorscale("turbo", [n/(n_colors -1) for n in range(n_colors)])

这里是完整的例子:

import plotly.graph_objects as go
import plotly.express as px

n_colors = 25
colors = px.colors.sample_colorscale("turbo", [n/(n_colors -1) for n in range(n_colors)])

fig = go.Figure()

# for i, c in enumerate(greys15):
for i, c in enumerate(colors):
    fig.add_bar(x=[i], y = [15], marker_color = c, showlegend = False, name=c)
f = fig.full_figure_for_development(warn=False)
fig.show()