python - 如何在 Python API 中使用 plotly 在 x 轴范围中位位置绘制垂直线?

标签 python plotly

我正在尝试绘制一条动态定位的垂直线,以便在进行过滤时,该线会相应移动。例如,使用下面的代码,我可以在 25K 处绘制一条静止的垂直线,它以整个数据集作为中值,但是当数据被过滤到“美洲”时,仅因为 x 轴范围现在是 45K,该线不再处于中间位置。

那么如何绘制一条位于 x 轴范围的中间位置的垂直线?谢谢

import pandas as pd
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot

init_notebook_mode(connected=True)


df = pd.read_csv('https://raw.githubusercontent.com/yankev/test/master/life-expectancy-per-GDP-2007.csv')

americas = df[(df.continent=='Americas')]
europe = df[(df.continent=='Europe')]

trace_comp0 = go.Scatter(
    x=americas.gdp_percap,
    y=americas.life_exp,
    mode='markers',
    marker=dict(size=12,
                line=dict(width=1),
                color="navy"
               ),
    name='Americas',
    text=americas.country,
    )

trace_comp1 = go.Scatter(
    x=europe.gdp_percap,
    y=europe.life_exp,
    mode='markers',
    marker=dict(size=12,
                line=dict(width=1),
                color="red"
               ),
    name='Europe',
    text=europe.country,
        )

data_comp = [trace_comp0, trace_comp1]
layout_comp = go.Layout(
    title='Life Expectancy v. Per Capita GDP, 2007',
    hovermode='closest',
    xaxis=dict(
        title='GDP per capita (2000 dollars)',
        ticklen=5,
        zeroline=False,
        gridwidth=2,
        range=[0, 50_000],
    ),
    yaxis=dict(
        title='Life Expectancy (years)',
        ticklen=5,
        gridwidth=2,
        range=[0, 90],
    ),
    shapes=[
        {
            'type': 'line',
            'x0': 25000,
            'y0': 0,
            'x1': 25000,
            'y1': 85,
            'line': {
                'color': 'black',
                'width': 1
            }
        }
    ]
)
fig_comp = go.Figure(data=data_comp, layout=layout_comp)
iplot(fig_comp)

enter image description here

最佳答案

在@rpanai 的回答和使用 plotly update 按钮的帮助下,开发了以下解决方案。检查这个。

import pandas as pd
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot

init_notebook_mode(connected=True)

df = pd.read_csv('https://raw.githubusercontent.com/yankev/test/master/life-expectancy-per-GDP-2007.csv')

americas = df[(df.continent=='Americas')]
europe = df[(df.continent=='Europe')]
# med_eur = europe["gdp_percap"].median()
# med_ame = americas["gdp_percap"].median()
# med_total=pd.DataFrame(list(europe["gdp_percap"])+list(americas["gdp_percap"])).median()[0]
med_eur = europe["gdp_percap"].max()/2
med_ame = americas["gdp_percap"].max()/2
med_total=25000

trace_median0 =  go.Scatter(x=[med_total, med_total],
                            y=[0,85],
                            mode="lines",
                            legendgroup="a",
                            showlegend=False,
                            marker=dict(size=12,
                                       line=dict(width=0.8),
                                       color="green"
                                       ),
                            name="Median Total"
                            )

trace_comp1 = go.Scatter(
    x=americas.gdp_percap,
    y=americas.life_exp,
    mode='markers',
    marker=dict(size=12,
                line=dict(width=1),
                color="navy"
               ),
    name='Americas',
    text=americas.country
    )

trace_median1 =  go.Scatter(x=[med_ame, med_ame],
                            y=[0,90],
                            mode="lines",
                            legendgroup="a",
                            showlegend=False,
                            marker=dict(size=12,
                                       line=dict(width=0.8),
                                       color="navy"
                                       ),
                            name="Median Americas",
                            visible=False
                            )
trace_comp2 = go.Scatter(
    x=europe.gdp_percap,
    y=europe.life_exp,
    mode='markers',
    marker=dict(size=12,
                line=dict(width=1),
                color="red"
               ),
    name='Europe',
    text=europe.country,
        )

trace_median2 =  go.Scatter(x=[med_eur, med_eur],
                            y=[0,90],
                            mode="lines",
                            legendgroup="b",
                            showlegend=False,
                            marker=dict(size=12,
                                       line=dict(width=0.8),
                                       color="red"
                                       ),
                            name="Median Europe",
                            visible=False
                            )

data_comp = [trace_comp1,trace_median1]+[trace_comp2,trace_median2]+[trace_median0]
layout_comp = go.Layout(
    title='Life Expectancy v. Per Capita GDP, 2007',
    hovermode='closest',
    xaxis=dict(
        title='GDP per capita (2000 dollars)',
        ticklen=5,
        zeroline=False,
        gridwidth=2,
        range=[0, 50_000],
    ),
    yaxis=dict(
        title='Life Expectancy (years)',
        ticklen=5,
        gridwidth=2,
        range=[0, 90],
    ),
    showlegend=False
)
updatemenus = list([
    dict(type="buttons",
         active=-1,
         buttons=list([
            dict(label = 'Total Dataset ',
                 method = 'update',
                 args = [{'visible': [True,False,True,False,True]},
                         {'title': 'Life Expectancy v. Per Capita GDP, 2007'}]),
            dict(label = 'Americas',
                 method = 'update',
                 args = [{'visible': [True,True, False, False,False]},
                         {'title': 'Americas'}]),
            dict(label = 'Europe',
                 method = 'update',
                 args = [{'visible': [False, False,True,True,False]},
                         {'title': 'Europe'}])
        ]),
    )
])

annotations = list([
    dict(text='Trace type:', x=0, y=1.085, yref='paper', align='left', showarrow=False)
])
layout_comp['updatemenus'] = updatemenus
layout_comp['annotations'] = annotations
fig_comp = go.Figure(data=data_comp, layout=layout_comp)
iplot(fig_comp)

enter image description here

enter image description here

关于python - 如何在 Python API 中使用 plotly 在 x 轴范围中位位置绘制垂直线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55586773/

相关文章:

python - 如何在 Python 中获取文件的 ctime 和/或 mtime,包括时区?

python - Pandas 无法打开 Excel (.xlsx) 文件

javascript - Plotly-Dash:如何确定客户端回调中的触发器输入

python - 多迹线图表上不必要的额外边距

python - 使用 python 打印时间戳的一部分

python - 改进模板标签的功能 - Django

python - 在 django cms 中以多种语言提供页面的最佳方法

python - 用python定位lib Orca

javascript - 以交互模式在 qwebview 中打开 plotly

r - Plotly 等高线图行为