有没有一种方法可以使用plotly在python中创建范围图?

时间:2020-08-02 07:36:56

标签: python matplotlib plotly-python

我能够创建一个简单的点图,但需要一种连接这些点的方法。
enter image description here

2 个答案:

答案 0 :(得分:2)

'Plotly'图是初学者的水平,我没有太多使用它们。我无法实现的两个功能是线条图颜色渐变以及“女性”和“男性”标签。此级别的效果不是很好,但请用作参考。

import pandas as pd
import numpy as np
import io

data = '''
 Grade Women Men
0 "Less Than 9th Grade" 21 34
1 "9th 12th(no degree)" 22 37
2 "Hight School" 29 47
3 "Some college, no degree" 35 53
4 "Associate Degree" 38 56
5 "Bachelor's Degree" 54 84
6 "Master's Degree" 69 99
7 "Doctorate Degree" 91 151
'''

df = pd.read_csv(io.StringIO(data), sep='\s+')
df.sort_values('Men', ascending=False, inplace=True, ignore_index=True)

import plotly.graph_objects as go
import plotly.figure_factory as ff

w_lbl = [str(s) for s in df['Women'].tolist()]
m_lbl = [str(s) for s in df['Men'].tolist()]

fig = go.Figure()

for i in range(0,8):
    fig.add_trace(go.Scatter(
        x=[df['Women'][i],df['Men'][i]],
        y=[df['Grade'][i],df['Grade'][i]],
        orientation='h',
        line=dict(color='rgb(244,165,130)', width=8),
             ))

fig.add_trace(go.Scatter(
    x=df['Women'],
    y=df['Grade'],
    marker=dict(color='#CC5700', size=14),
    mode='markers+text',
    text=w_lbl,
    textposition='middle left',
    name='Woman'))

fig.add_trace(go.Scatter(
    x=df['Men'],
    y=df['Grade'],
    marker=dict(color='#227266', size=14),
    mode='markers+text',
    text=m_lbl,
    textposition='middle right',
    name='Men'))

fig.update_layout(title="Sample plotly", showlegend=False)


fig.show()

enter image description here

答案 1 :(得分:2)

我对@r-beginners code进行了稍微的编辑,以便为线条,注释及其颜色添加颜色渐变。关于颜色渐变,如暴露的here

该功能尚不适用于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()

图:

enter image description here