1. 3個plotly實用進階范例~

        共 9586字,需瀏覽 20分鐘

         ·

        2024-05-28 09:39

        本文介紹3個plotly非常實用的高級操作范例:

        1,繪制時間序列設(shè)置滑塊;

        2,繪制地圖設(shè)置高德底圖;

        3,使用dash構(gòu)建交互面板;

        公眾號后臺回復(fù)關(guān)鍵詞:plotly,獲取本文jupyter notebook 源代碼~

        一,繪制時間序列設(shè)置滑塊

        可以使用一個滑塊來選擇繪圖時間范圍。

        import plotly.express as px 
        dfdata = px.data.stocks()

        fig = px.line(data_frame=dfdata, x = 'date',y = ['GOOG''AAPL''AMZN''FB''NFLX''MSFT'])
        fig.update_xaxes(dtick="M2",tickformat="%Y-%m-%d",rangeslider=dict(visible=True),
                     rangeselector={'buttons': [{'count'7,
                       'label''1w',
                       'step''day',
                       'stepmode''backward'},
                      {'count'1'label''1m''step''month''stepmode''backward'},
                      {'count'6'label''6m''step''month''stepmode''backward'},
                      {'count'1'label''1y''step''year''stepmode''backward'},
                      {'step''all'}]}
                    )
        fig.update_layout(#autosize=True,
            #width=1000, 
            #height=600,
            margin=dict(
                r=0, t=0, l=0, b=0, pad=0)
            )
        fig.show()
        fig.write_html('test.html')

        效果如下:

        二,繪制地圖設(shè)置高德底圖

        plotly繪制地圖可以使用高德底圖。


        import plotly.express as px 
        dfdata = pd.DataFrame({'lat'39 + np.random.rand(100),
                                'lon'116+np.random.rand(100),
                               'color'10*np.random.rand(100),
                               'size'0.5*np.random.rand(100),
                              })

        fig = px.scatter_mapbox(dfdata, lat="lat"
                                lon="lon", color="color",
                                size="size",            
                                color_continuous_scale=px.colors.cyclical.IceFire, 
                                size_max=15, zoom=10
                               )
        basemap_layer = [
            dict(
                below="traces",
                sourcetype="raster",
                sourceattribution="高德地圖",
                source=[
                    "http://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7"
                ]
            )
        ]

        fig.update_mapboxes(style='white-bg',zoom=7,layers=basemap_layer)
        fig.update_layout(margin=dict(r=0, t=0, l=0, b=0, pad=0))
        fig.show()

        效果如下:

        三,使用dash構(gòu)建交互面板

        使用plotly的dash可以讓做出非常豐富的前端交互效果。

        詳情參考:https://dash.plotly.com/

        import dash
        from dash import Dash, dcc, html, Input, Output
        import plotly.express as px


        external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

        template_list = ['plotly','ggplot2''seaborn''simple_white',
                 'plotly_white''plotly_dark''presentation''xgridoff',
                 'ygridoff''gridon']

        # 1,生成示例數(shù)據(jù)
        dfdata = px.data.stocks()


        # 2, 創(chuàng)建Dash app
        app = Dash(__name__,external_stylesheets=external_stylesheets)

        # 3, 設(shè)計頁面布局
        app.layout = html.Div([
            html.H3(children='頭部互聯(lián)網(wǎng)美股走勢數(shù)據(jù)'),
            dcc.Graph(id='stock-plot'),
            html.Br(),
            html.Label('template'),
            dcc.Slider(
                id='template',
                min=0,
                max=len(template_list)-1,
                value=0,
                marks={i: template_list[i] for i in range(len(template_list))},
                step=1
            ),
            html.Label('font_size'),
            dcc.Slider(
                id='font_size',
                min=10,
                max=20,
                value=15,
                marks={i: str(i) for i in range(10,21)},
                step=1
            )
            
        ])

        # 4, 編寫回調(diào)函數(shù)
        @app.callback(
            Output(component_id='stock-plot', component_property='figure'),
            [Input(component_id='template',  component_property='value'),
             Input(component_id='font_size', component_property='value')
            ]
        )
        def update_figure(template,font_size):
            fig = px.line(data_frame=dfdata, x = 'date',y = ['GOOG''AAPL''AMZN''FB''NFLX''MSFT'])
            fig.update_xaxes(dtick="M1",tickformat="%Y-%m-%d",rangeslider=dict(visible=True),
                         rangeselector={'buttons': [{'count'7,
                           'label''1w',
                           'step''day',
                           'stepmode''backward'},
                          {'count'1'label''1m''step''month''stepmode''backward'},
                          {'count'6'label''6m''step''month''stepmode''backward'},
                          {'count'1'label''1y''step''year''stepmode''backward'},
                          {'step''all'}]}
                        )
            fig.layout.template = template_list[template]
            fig.update_layout(autosize=True,
                #width=1000, 
                #height=600,
                margin=dict(
                    r=0, t=0, l=0, b=0, pad=0)
                )
            fig.update_layout({"font.size":font_size})
            return fig


        # 5, 運行交互頁面
        if __name__ == '__main__':
            app.run_server(debug=True)
            #app.run(jupyter_mode="tab") #'inline', 'external', 'jupyterlab', 'tab'

        運行上述代碼,會彈出一個可以交互的網(wǎng)頁,效果如下:


        猜你喜歡:


        Plotly深入淺出


        瀏覽 65
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
          
          

            1. 国产十大尺度真做无删减电影 | 娇妻4p被八个男人伺候电影 | 97色色五月天 | 成人无码中文字幕毛片视频 | 国产主播第一页 |