繁体   English   中英

带有 Plotly 的动画饼图

[英]Animated pie chart with Plotly

我将以下数据存储在 pandas dataframe 中。

import pandas as pd
 
values = [[4500, 2500, 1053, 500],
          [872, 2389, 819, 765],
          [293, 1668, 873, 778],
          [1656, 861, 6137, 698]]

df = pd.DataFrame(values, columns=['A', 'B', 'C', 'D'])
print(df.to_markdown())
Output:
|    |    A |    B |    C |   D |
|---:|-----:|-----:|-----:|----:|
|  0 | 4500 | 2500 | 1053 | 500 |
|  1 |  872 | 2389 |  819 | 765 |
|  2 |  293 | 1668 |  873 | 778 |
|  3 | 1656 |  861 | 6137 | 698 |

我可以使用 plotly (使用 px.pie 或 go.Pie) plot 单行饼图。 这里我 plot 最后一行的数据。

import plotly.graph_objects as go
fig = go.Figure(data=[go.Pie(labels=df.columns, values=df.iloc[-1])])
fig.show()

有没有一种方法可以创建一个动画饼图,该饼图将逐行显示每一行的数据。 似乎 plotly express 支持 animation 用于散点图和条形图,但我找不到与饼图相关的任何内容。 注意:我只是在使用 plotly 寻求帮助。 我确实知道如何使用 matplotlib 做到这一点。

可以在 R 中使用当前版本的 plotly,我不知道 python 语法,但在定义变量时指定变量“frame”可能会起作用。 在 R 中,框架定义了随框架变化的尺寸,并且此功能可能会延续。 我已经成功使用它,我从https://plotly.com/r/animations/得到了最初的建议

它可能看起来如何

fig = go.Figure(data=[go.Pie(labels=df.columns, values=df.iloc[-1])]
,frame= row
)

希望 plotly 在两种语言中的工作方式有足够的交叉,以便对此有所帮助。

参考

查看Plotly 文档中的“简单播放按钮”和“使用 Slider 和按钮”部分

代码

import plotly.graph_objects as go
import pandas as pd
import plotly.io as pio
pio.renderers.default = 'browser'

values = [[4500, 2500, 1053, 500],
          [872, 2389, 819, 765],
          [293, 1668, 873, 778],
          [1656, 861, 6137, 698]]
headings =['A', 'B', 'C', 'D']
df = pd.DataFrame(values, columns = headings)

# create a dictionary
fig_dict = {
    "data": [],
    "layout": {},
    "frames": []
}

# create initial frame
initial_frame_values = df.iloc[0]

# add initial frame to dictionary
fig_dict["data"] = [go.Pie(labels=headings,
                           title="frame : 0",
                           values=initial_frame_values,
                           sort=False)]

# Loop through each row of df to create a list of frames 
# that will be displayed when Play button is pressed.
frames_list = []
for index, row in df.iterrows():
    current_frame_title = "frame : " + str(index+1)
    frames_list.append(
        go.Frame(data=[go.Pie(labels=headings,
                              values=row,
                              title=current_frame_title,
                              sort=False)])
    )

# create buttons for animations : Play, Pause
fig_dict["layout"]["updatemenus"] = [{
    "buttons": [{
            "args": [None, {
                "frame": {
                    "duration": 2000, # affects playback speed
                                "redraw": True
                },
                "fromcurrent": True,
                            "transition": {
                    "duration": 1000
                }
            }],
            "label": "Play",
                    "method": "animate"
        },
        {
            "args": [
                [None], {
                    "frame": {
                        "duration": 0,
                        "redraw": True
                    },
                    "mode": "immediate",
                    "transition": {
                        "duration": 0
                    }
                }
            ],
            "label": "Pause",
            "method": "animate"
        }
    ],
    "pad": {
        "r": 10,
        "t": 87
    },
    "showactive": False,
    "type": "buttons",
    "x": 0.1,
    "xanchor": "right",
    "y": 0,
    "yanchor": "top"
}]
# add our list of frames to our dictionary
fig_dict["frames"] = frames_list

# create final figure
fig = go.Figure(fig_dict)

# optional
fig_dict["layout"]["title"] = "my pie chart"
fig.update_layout(legend_title_text='stuffs')

fig.show()

结果

在按下播放按钮之前

在此处输入图像描述

按下播放键后

在此处输入图像描述

在此处输入图像描述

帧 3

在此处输入图像描述

笔记

  • 我的图像被裁剪并排除了播放和暂停按钮以及图例。

  • 帧 0 和 1 相同。

  • 在按下播放按钮之前,仅显示第 0 帧。

  • 按下播放按钮后,将显示第 1-4 帧,然后 animation 停止。

  • 再次按下播放按钮时,将再次显示第 1-4 帧,然后 animation 停止。 请注意,之后省略了第 0 帧。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM