Я немного отредактировал код @ r-beginners , чтобы добавить градиент цвета к строке, аннотациям и их цвету. Что касается цветового градиента, как показано здесь :
Эта функция еще не доступна для линейных 2D-графиков, в настоящее время она доступна только для линейных 3D-графиков, см. https://github.com/plotly/plotly.js/issues/581. Однако можно использовать шкалу цветов на 2D-графике, если вы используете маркеры вместо линий, см. Пример ниже.
Вот мой код:
import pandas as pd
import numpy as np
import plotly.graph_objects as go
df = pd.DataFrame({'Grade': ["Doctorate Degree",
"Master's Degree",
"Bachelor's Degree",
"Associate Degree",
"Some college, no degree",
"Hight School",
"9th 12th(no degree)",
"Less Than 9th Grade"],
'Women': [91, 69, 54, 38, 35, 29, 22, 21],
'Men': [151, 99, 84, 56, 53, 47, 37, 34]})
w_lbl = list(map(lambda x: str(x), df['Women']))
m_lbl = list(map(lambda x: str(x), df['Men']))
fig = go.Figure()
for i in range(0, len(df)):
fig.add_trace(go.Scatter(x = np.linspace(df['Women'][i], df['Men'][i], 1000),
y = 1000*[df['Grade'][i]],
mode = 'markers',
marker = {'color': np.linspace(df['Women'][i], df['Men'][i], 1000),
'colorscale': ['#E1A980', '#8DAEA6'],
'size': 8}))
fig.add_trace(go.Scatter(x = df['Women'],
y = df['Grade'],
marker = dict(color = '#CC5600', size = 14),
mode = 'markers+text',
text = w_lbl,
textposition = 'middle left',
textfont = {'color': '#CC5600'},
name = 'Woman'))
fig.add_trace(go.Scatter(x = df['Men'],
y = df['Grade'],
marker = dict(color = '#237266', size = 14),
mode = 'markers+text',
text = m_lbl,
textposition = 'middle right',
textfont = {'color': '#237266'},
name = 'Men'))
fig.add_annotation(x = df.iloc[-1, df.columns.get_loc('Women')] - 5,
y = df.iloc[-1, df.columns.get_loc('Grade')],
text = 'Women',
font = {'color': '#CC5600',
'size': 15},
showarrow = False)
fig.add_annotation(x = df.iloc[-1, df.columns.get_loc('Men')] + 5,
y = df.iloc[-1, df.columns.get_loc('Grade')],
text = 'Men',
font = {'color': '#237266',
'size': 15},
showarrow = False)
fig.update_layout(title = "Sample plotly",
showlegend = False)
fig.show()
Plot:
введите описание изображения здесь