更新菜单后不可见的绘图痕迹

2024-06-24 12:53:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一张美国地图上绘制分散的地理图(51个州包括华盛顿州和4个不同年份的4个记录道)。我有2个按钮,在一个带有图例的散点地理(51个记录道)和另一个底部有滑块(4个记录道)的散点地理之间切换。我最初设置了4条记录道(年)visible = False,因为我只希望最初显示51条记录道,但当我单击按钮用滑块切换到scattergeo,并设置了前51条记录道visible = False和最后4条记录道visible = [True, False, False, False]地图上看不到我的记录道。在

不知道为什么会这样。当我设置cities_yearvisible = True时,当第一次创建scattergeo(即它们最初是可见的)时,轨迹会出现,但我不希望这样,因为这样我的所有散射点都会在彼此上绘制两次。在

下面是一些创建数据集的代码:

data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv')
data = data.iloc[:400] # Keep only first 400 samples
data.loc[:100, 'year'] = '1990'
data.loc[100:200, 'year'] = '1991'
data.loc[200:300, 'year'] = '1992'
data.loc[300:, 'year'] = '1993'

我正在使用plotly 2.7.0版和脱机打印 下面是我的代码:

^{pr2}$

Tags: falsetruedata记录地图绘制year按钮
1条回答
网友
1楼 · 发布于 2024-06-24 12:53:56

问题:如果我理解正确的话,当上面的code运行时,iplot()创建了scattergeo()图,其中两个buttons标记为statesyears。在这两个按钮中,'states'按钮处于活动状态,并显示其绘图(带有“红点”和legend)。“years”按钮对应于带有slider选项的绘图(years1990到{})。现在,当点击这个“years”按钮时,期望的是“红点”应该出现在maps(对于year1990)的上方。然而,这种情况不会发生。在

运行上述代码时绘制Plot when above code is run

点击“年份”按钮时,enter image description here

尝试的解决方案:

visible被设置为citydictionarycities_yearlist中的True(下面),问题就解决了。也就是说,在code运行之后,绘图会出现两个按钮。现在当“yearsbuttonclicked,它在year1990处显示带有slider的“红点”。设置visible=True可能很重要,因为它可能是加载或显示plot的第一个实例。(Jupyter Notebook 5.0.0Python 3.6.6

cities_year = []
for year in sorted(data.year.value_counts().index):
    data_sub = data.loc[data['year'] == year]
    city = dict(
        type = 'scattergeo',
        visible = True,

运行code后绘制: enter image description here

现在,当点击“年份”按钮时,图为: enter image description here

编辑-1

slider仍然无法按预期工作。但是找到了一个解决方法,只使用legends来选择year。在

^{pr2}$

enter image description here

编辑-2

这个问题仍然没有解决,但是下面的代码可能有助于缩小查找错误的范围。在下面的code中,有两个样本数据集:(1)go.Scatter()和(2)go.Scattergeo()。为了简单起见,每个dataframe中总共只有5rows。请注意,尽管用于生成示例数据集的code是不同的,但是下面的代码将绘制上述两个数据集。它表明go.Scatter()工作良好,go.Scattergeo()存在问题中提到的问题。在

导入库

import datetime
from datetime import date
import pandas as pd
import numpy as np
from plotly import __version__
%matplotlib inline

import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot 
init_notebook_mode(connected=True)

init_notebook_mode(connected=True)
cf.go_offline()

import plotly.offline as pyo
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

import json

go.Scatter()创建数据

# Create random numbers
x = np.random.randn(100)
y = 10 + np.random.randn(100)
z = np.linspace(-3,2,100)
df = pd.DataFrame({'x':x, 'y':y, 'z':z})
df.head(2)

# Create traces
trace1 = go.Scatter(visible = True, x=df.x, y=df.y, mode='markers', name='trace1', marker=dict(color='red'))
trace2 = go.Scatter(visible = True, x=df.x, y=df.z, mode='markers', name='trace2', marker=dict(color='black'))

trace3 = go.Scatter(visible = False, x=df.x, y=df.y*df.y, mode='markers', name='trace3', marker=dict(color='blue'))
trace4 = go.Scatter(visible = False, x=df.x, y=df.z*0.5, mode='markers', name='trace4', marker=dict(color='orange'))
trace5 = go.Scatter(visible = False, x=df.x, y=df.z*df.z, mode='markers', name='trace5', marker=dict(color='purple'))

# Create list of traces 
data = [trace1, trace2, trace3, trace4, trace5]

go.Scattergeo()创建数据

# Create dataframe for cities
df = pd.DataFrame({'name': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia'],
                  'pop': [8287238, 3826423, 2705627, 2129784, 1539313],
                  'lat': [40.730599, 34.053717, 41.875555, 29.758938, 39.952335],
                  'lon': [-73.986581, -118.242727, -87.624421, -95.367697, -75.163789],
                   'year': [1990, 1991, 1992, 1993, 1991]
                })


# Create city traces manually without for-loop
trace1 = go.Scattergeo(visible=True,name = 'trace1',locationmode = 'USA-states',
                   lon = df[df['name']=='New York']['lon'], lat = df[df['name']=='New York']['lat'], 
                   mode = 'markers',marker = dict(size=10, symbol='circle-open', color = "red")) 
trace2 = go.Scattergeo(visible=True,name = 'trace2',locationmode = 'USA-states',
                   lon = df[df['name']=='Los Angeles']['lon'], lat = df[df['name']=='Los Angeles']['lat'], 
                   mode = 'markers',marker = dict(size=10, symbol='circle-open', color = "red")) 


trace3 = go.Scattergeo(visible=False, name = 'trace3', locationmode = 'USA-states',
                   lon = df[df['year']==1990]['lon'], lat = df[df['year']==1990]['lat'],
                   mode = 'markers',marker = dict(size=20, symbol='circle-open', color = "blue")
                  ) 
trace4 = go.Scattergeo(visible=False, name = 'trace4', locationmode = 'USA-states',
                   lon = df[df['year']==1991]['lon'], lat = df[df['year']==1991]['lat'],
                   mode = 'markers',marker = dict(size=20, symbol='circle-open', color = "blue")
                  )  
trace5 = go.Scattergeo(visible=False, name = 'trace5', locationmode = 'USA-states',
                   lon = df[df['year']==1992]['lon'], lat = df[df['year']==1992]['lat'],
                   mode = 'markers',marker = dict(size=20, symbol='circle-open', color = "blue")
                  ) 

# Create list of traces
data = [trace1, trace2, trace3, trace4, trace5]

Code以下是上述两个数据集的共同点

# Create slider
sliders = [dict(active=-1,
               pad = {"t": 1},
               currentvalue = {"prefix": "Plot Number: "},
               execute=True, 
               steps = [
                        dict(args = ["visible", [False, False, True, False, False]],
                             label = "trace3", 
                             method = "restyle"
                            ),
                        dict(args = ["visible", [False, False, False,True, False]],
                             label = "trace4",
                             method = "restyle"
                            ),
                        dict(args = ["visible", [False, False, False, False, True]],
                             label = "trace5",
                             method = "restyle"
                            )
                       ],
                transition = 0
              )
         ]

# Create updatemenus
updatemenus = list([
    dict(
        buttons= list([
                        dict(
                             args = [
                                    {'visible': (True, False, False, False, False)},
                                    {'sliders':[], 'showlegend': True, 'title': 'Plots only'}
                                    ],
                             label = 'single_plot',
                             method = 'update'

                    ),
                         dict(
                             args = [
                                    {'visible': (False, False, True, False, False)},
                                    {'sliders':sliders, 'showlegend': True, 'title': 'Plots with slider'}
                                    ],
                             label = 'multi_plots',
                             method = 'update'

                    )
        ]),
        direction = 'left',
        pad = {'r': 10, 't': 10},
        showactive = True,
        type = 'buttons',
        x = 0.1,
        xanchor = 'left',
        y = 1,
        yanchor = 'top' 
    )])

# Create layout
layout = go.Layout(title='Chart') #, geo=dict(scope='usa')) #< uncomment for Scattergeo() ... optional
layout['updatemenus'] = updatemenus

# Plot data
fig = go.Figure(data=data, layout=layout)
pyo.offline.plot(fig)

go.Scatter()绘制

(左:绘制button'single_plot';右:绘制button'multi_plots')

注意,按“多点”button后,右侧数据点的绘图正确显示。在

enter image description here

go.Scattergeo()绘制

(左:绘制button'single_plot';右:绘制button'multi_plots')

注意,在这里,按下“multi_points”按钮后,右侧的绘图中缺少数据点。在

enter image description here

相关问题 更多 >