【问题标题】:What is a good way to install an interactive filter in python plotly?在 python 中安装交互式过滤器的好方法是什么?
【发布时间】:2021-05-10 11:57:52
【问题描述】:

我想在 python 中安装一个下拉过滤器 - 不使用破折号。

我想出的解决方案适用于 xaxis/yaxis 范围不改变的情况,例如热图。如果范围发生变化,它就不能再正常工作了。

示例:包含国家/地区信息的条形图。适用于意大利和加拿大。如果我切换到人口数量高于初始国家意大利的德国,则 y 轴范围不会增加。这怎么可能解决?或者一般来说有没有更有效的方法?

非常感谢您提供有用的建议!

例子:

# Data
df = px.data.gapminder()
df = df[['country','year', 'pop']]
df.head(3)
# Create Barchart
def generate_barchart(ins):
    fig = px.bar(df[df['country']==ins], x='year', y='pop')
    return fig

# Dropdown: Content
uplist1 = ['Italy', 'Canada', 'Germany']
uplist2 = [generate_barchart(ins) for ins in uplist1]

# Dropdown: Implementation
upfilter = [{'method': 'animate', 'label': i1, 'args': [i2]} for i1, i2  in zip(uplist1, uplist2)]
updatemenus = [{'buttons': upfilter}]

# Initial barchart
fig = go.Figure(uplist2[0])

# Add dropdown
fig.update_layout(updatemenus=updatemenus)

# Result
fig

适用于意大利和加拿大:

超出范围:

【问题讨论】:

    标签: python plotly dropdown


    【解决方案1】:

    我看到两个选项如何使 Y 轴正确(除了手动重置它)。两者都为 Y 轴设置了 range

    1. 这已经差不多了,除了动画有点过时(酒吧可能会去 超出或超出视口)。

      def generate_barchart(ins):
          plot_df = df[df['country'] == ins]
          fig = px.bar(plot_df, x='year', y='pop')
          fig.update_yaxes(range=[plot_df['pop'].min(), plot_df['pop'].max()])
          return fig
      

      要修复它,您可以通过这种方式制作按钮来禁用动画效果。

      upfilter = [
          {
              'method': 'animate', 
              'label': i1, 
              'args': [
                  i2, 
                  {
                      'frame': {'duration': 0, 'redraw': False},
                      'mode': 'immediate',
                      'transition': {'duration': 0},
                  },
              ]
          } 
          for i1, i2 in zip(uplist1, uplist2)
      ]
      
    2. 您也可以定义跨国家/地区的范围。

      def generate_barchart(ins):
          fig = px.bar(df[df['country'] == ins], x='year', y='pop')
          fig.update_yaxes(range=[
              df[df['country'].isin(uplist1)]['pop'].min(), 
              df[df['country'].isin(uplist1)]['pop'].max(),
          ])
          return fig
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多