1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        7000字 23張圖,Pandas一鍵生成炫酷的動態(tài)交互式圖表

        共 6573字,需瀏覽 14分鐘

         ·

        2021-11-09 14:01


        今天小編來演示一下如何用pandas一行代碼來繪制可以動態(tài)交互的圖表,并且將繪制的圖表組合到一起,組成可視化大屏,本次小編將要繪制的圖表有

        • 折線圖
        • 散點圖
        • 直方圖
        • 柱狀圖
        • 餅圖
        • 面積圖
        • 地圖
        • 組合圖

        準備工作

        我們先導入需要用到的庫,并做相應的設置

        import?pandas?as?pd
        import?pandas_bokeh
        pandas_bokeh.output_notebook()

        因為小編是在jupyter nobteook上面操作的,這邊就用到了output_notebook()的設置

        折線圖

        我們先來畫一張簡單的折線圖,當中隨機生成一批數(shù)據(jù)

        import?numpy?as?np

        np.random.seed(55)
        df?=?pd.DataFrame({"寧德時代":?np.random.randn(100)+0.2,?
        ???????????????????"貴州茅臺":?np.random.randn(100)+0.17},?
        ???????????????????index=pd.date_range('1/1/2021',?periods=100))
        df?=?df.cumsum()
        df?=?df?+?50
        df.plot_bokeh(kind="line")?

        output

        繪制出來的圖表可以任意的縮放以及拖拽,我們也可以點擊右邊的“保存”按鈕來實現(xiàn)對圖表的下載保存,以至于圖表的類型只需要對參數(shù)kind加以設定,我們將上面的代碼優(yōu)化一下
        df.plot_bokeh.line(
        ????figsize=(800,?450),
        ????title="寧德時代?vs?貴州茅臺",
        ????xlabel="日期",
        ????ylabel="股票價格?[$]",
        ????yticks=[0,?100,?200,?300,?400],
        ????ylim=(0,?100),
        ????xlim=("2021-01-01",?"2021-04-01"),
        ????colormap=["red",?"blue"],
        ????plot_data_points=True,
        ????plot_data_points_size=10,
        ????marker="asterisk")

        output

        我們對X軸以及Y軸坐標做了范圍的限定,并且加上了標注,效果看起來也更加的美觀一些。和pyecharts類似,我們也可以在圖標的底部添加一個時間軸,拖動時間軸來展示數(shù)據(jù)
        ts?=?pd.Series(np.random.randn(100),?index=pd.date_range('1/1/2021',?periods=100))
        df?=?pd.DataFrame(np.random.randn(100,?4),?index=ts.index,?columns=list('ABCD'))
        df?=?df.cumsum()

        df.plot_bokeh(rangetool=True)

        output

        當然我們也可以對折線加以修改,就可以變成另外一種樣子,主要修改的就是參數(shù)marker
        x?=?np.arange(-5,?5,?0.1)
        y2?=?x**2
        y3?=?x**3
        df?=?pd.DataFrame({"x":?x,?"Type?1":?y2,?"Type?2":?y3})
        df.plot_bokeh.point(
        ????x="x",
        ????xticks=range(-5,?5),
        ????size=5,
        ????colormap=["#009933",?"#ff3399"],
        ????title="折線圖?(Type?1?vs.?Type?2)",
        ????marker="x")

        output

        散點圖

        接下來我們來看散點圖,步驟與上述的折線圖相類似

        df?=?pd.read_csv("iris.csv")
        p_scatter?=?df.plot_bokeh.scatter(
        ????x="petal?length(cm)",
        ????y="sepal?width(cm)",
        ????category="species",
        ????title="Iris數(shù)據(jù)集可視化",
        ????show_figure=True,
        )

        output

        我們在讀取了iris數(shù)據(jù)集之后,將x參數(shù)和y參數(shù)上填上我們所要繪制的兩列,而title參數(shù)則是設置圖表的標題

        我們也可以通過當中size這個參數(shù)來控制散點的大小,例如

        df.loc[13,?"sepal?length(cm)"]?=?15
        df.loc[15,?"sepal?length(cm)"]?=?17
        df.loc[20,?"sepal?length(cm)"]?=?30
        df.loc[40,?"sepal?length(cm)"]?=?20

        p_scatter?=?df.plot_bokeh.scatter(
        ????x="petal?length(cm)",
        ????y="sepal?width(cm)",
        ????category="species",
        ????title="Iris數(shù)據(jù)集可視化",
        ????show_figure=True,
        ????size="sepal?length(cm)"
        )

        output

        柱狀圖

        下面我們來看一下直方圖的繪制

        data?=?{
        ????'fruits':
        ????['蘋果',?'梨',?'草莓',?'西瓜',?'葡萄',?'香蕉'],
        ????'2015':?[2,?1,?4,?3,?2,?4],
        ????'2016':?[5,?3,?3,?2,?4,?6],
        ????'2017':?[3,?2,?4,?4,?5,?3]
        }
        df?=?pd.DataFrame(data).set_index("fruits")

        p_bar?=?df.plot_bokeh.bar(
        ????ylabel="每斤的的價格?[¥]",?
        ????title="水果每年的價格",?
        ????alpha=0.6)

        output

        我們看到上面的直方圖是按照不同的年份分開來的,我們也可以堆疊起來,通過stacked這個參數(shù)來實現(xiàn)
        p_stacked_bar?=?df.plot_bokeh.bar(
        ????ylabel="每斤的的價格?[¥]",
        ????title="水果每年的價格",
        ????stacked=True,
        ????alpha=0.6)

        output

        直方圖

        繪制直方圖的方式也是類似的

        p_hist?=?df_hist.plot_bokeh.hist(
        ????y=["a",?"b"],
        ????bins=np.arange(-5,?5,?0.5),
        ????normed=100,
        ????vertical_xlabel=True,
        ????ylabel="Share[%]",
        ????title="正則分布直方圖",
        ????show_average=True,
        ????xlim=(-4,?6),
        ????ylim=(0,?30),
        ????show_figure=True)

        output

        小編個人覺得直方圖有點丑,不知道大家是不是有類似的體驗

        面積圖

        df.plot_bokeh.area(
        ????x="Year",
        ????stacked=True,
        ????legend="top_left",
        ????colormap=["yellow",?"orange",?"black",?"grey",?"blue",?"green"],
        ????title="全球不同能源的消耗量",
        ????ylabel="不同能源的消耗(噸)",
        ????ylim=(0,?16000))

        output

        我們看到石油的消耗量一直都在不斷的提升,另外有一個normed參數(shù)來幫助我們更好的觀察數(shù)據(jù)的走勢
        df.plot_bokeh.area(
        ????x="Year",
        ????stacked=True,
        ????normed?=?100,
        ????legend="bottom_left",
        ????colormap=["yellow",?"orange",?"black",?"grey",?"blue",?"green"],
        ????title="全球不同能源的消耗量",
        ????ylabel="不同能源的消耗(噸)")

        output

        餅圖

        df_pie.plot_bokeh.pie(
        ????x="Type",
        ????y="2017",
        ????colormap=["blue",?"red",?"yellow",?"green",?"purple",?"orange",?"grey"],
        ????title="餅圖",
        ????)

        output

        上面的代碼只是引用了表格當中的一列,當然我們也可以不做指定,引用表格當中的每一列數(shù)據(jù)
        df_pie.plot_bokeh.pie(
        ????x="Type",
        ????colormap=["blue",?"red",?"yellow",?"green",?"purple",?"orange",?"grey"],
        ????title="多重餅圖",
        ????line_color="black")

        output

        地圖

        同時我們來看一下地圖的繪制,下面的圖表是基于全球各大城市的人口密度分布來繪制的
        df_mapped.plot_bokeh.map(
        ????x="longitude",
        ????y="latitude",
        ????hovertool_string="""

        ?@{name}?

        ?
        ????
        ????????????????????????

        ?Population:?@{pop_max}?

        "
        "",
        ????tile_provider="STAMEN_TERRAIN_RETINA",
        ????size="population",?
        ????figsize=(900,?600),
        ????title="全球特大城市分布")

        output

        從圖中可以看出,亞洲的日本主要是集中在東京這塊,而像在國內(nèi)的話,有大家熟知的北上廣深。上面的代碼有兩個參數(shù)xy分別對應的是經(jīng)緯度,
        import?geopandas?as?gpd
        import?pandas_bokeh
        pandas_bokeh.output_file("Interactive?Plot.html")

        df_states?=?gpd.read_file("states.geojson")
        print(df_states.head())
        下面這張圖是美國各個州2017年的的人口總量,我們給上面的每一個州配上不同的顏色
        df_states.plot_bokeh(
        ????figsize=(900,?600),
        ????category="POPESTIMATE2017",
        ????simplify_shapes=5000,
        ????colormap="Inferno",
        ????colormap_uselog=True,
        ????colorbar_tick_format="0.0a")

        output

        當然我們也可以在地圖上面添加一個時間軸,讓圖表隨著時間的流逝而變化

        for?i?in?range(8):
        ????df_states["Delta_Population_201%d"%i]?=?((df_states["POPESTIMATE201%d"%i]?/?df_states["POPESTIMATE2010"])?-1?)?*?100
        ????
        slider_columns?=?["Delta_Population_201%d"%i?for?i?in?range(8)]
        slider_range?=?range(2010,?2018)
        df_states.plot_bokeh(
        ????figsize=(900,?600),
        ????simplify_shapes=5000,
        ????slider=slider_columns,
        ????slider_range=slider_range,
        ????slider_name="Year",
        ????colormap="Inferno",
        ????hovertool_columns=["STATE_NAME"]?+?slider_columns,
        ????title="Change?of?Population?[%]")

        output

        同時我們也可以在地圖上面添加一個下拉框,通過點選來篩選數(shù)據(jù)的展示

        df_states["STATE_NAME_SMALL"]?=?df_states["STATE_NAME"].str.lower()

        df_states.plot_bokeh(
        ????figsize=(900,?600),
        ????simplify_shapes=5000,
        ????dropdown=["POPESTIMATE2010",?"POPESTIMATE2017"],
        ????colormap="Viridis",
        ????hovertool_string="""
        ????????????????????????"?
        ????????????????????????height="
        42"?alt="@imgs"?width="42"
        ????????????????????????style="
        float:?left;?margin:?0px?15px?15px?0px;"
        ????????????????????????border="
        2">
        ????????????????
        ????????????????????????

        ??@STATE_NAME?


        ????????????????????????

        ?2010:?@POPESTIMATE2010?


        ????????????????????????

        ?2017:?@POPESTIMATE2017?

        "
        "",
        ????tile_provider_url=r"http://c.tile.stamen.com/watercolor/{Z}/{X}/{Y}.jpg",
        ????tile_attribution='Map?tiles?by?Stamen?Design,?under?CC?BY?3.0.?Data?by?OpenStreetMap,?under?ODbL.'
        ????)

        output

        最后我們可以通過區(qū)域的篩選來進行數(shù)據(jù)的呈現(xiàn),通過`category`這個參數(shù)來實現(xiàn)
        df_states.plot_bokeh(
        ????figsize=(900,?600),
        ????simplify_shapes=5000,
        ????category="REGION",
        ????show_colorbar=False,
        ????colormap=["blue",?"yellow",?"green",?"red"],
        ????hovertool_columns=["STATE_NAME",?"REGION"],
        ????tile_provider="STAMEN_TERRAIN_RETINA")

        多圖組合

        pandas_bokeh模塊也能夠?qū)崿F(xiàn)多張圖表的組合,例如上面 人口密度的圖表就可以和美國各大洲的人口總量的圖表進行組合
        #繪制出大致的輪廓圖
        figure?=?df_states.plot_bokeh(
        ????figsize=(800,?450),
        ????simplify_shapes=10000,
        ????show_figure=False,
        ????xlim=[-170,?-80],
        ????ylim=[10,?70],
        ????category="REGION",
        ????colormap="Dark2",
        ????legend="States",
        ????show_colorbar=False,
        )

        #繪制人口的密度圖
        df_cities.plot_bokeh(
        ????figure=figure,?????????#?<==?pass?figure?here!
        ????category="pop_max",
        ????colormap="Viridis",
        ????colormap_uselog=True,
        ????size="size",
        ????hovertool_string="""

        @name


        ????????????????????????

        Population:?@pop_max?

        "
        "",
        ????marker="inverted_triangle",
        ????legend="Cities",
        )

        上面的代碼我們主要是用到了pandas_bokeh.plot_grid這個方法來將多個圖結(jié)合起來,再來看幾個簡單的案例
        df?=?pd.read_csv("iris.csv")

        from?bokeh.models.widgets?import?DataTable,?TableColumn
        from?bokeh.models?import?ColumnDataSource

        data_table?=?DataTable(
        ????columns=[TableColumn(field=Ci,?title=Ci)?for?Ci?in?df.columns],
        ????source=ColumnDataSource(df),
        ????height=300,
        )

        #?創(chuàng)建散點圖:
        p_scatter?=?df.plot_bokeh.scatter(
        ????x="petal?length(cm)",
        ????y="sepal?width(cm)",
        ????category="species",
        ????title="Iris數(shù)據(jù)可視化",
        ????show_figure=False,
        )

        #?Combine?Table?and?Scatterplot?via?grid?layout:
        pandas_bokeh.plot_grid([[data_table,?p_scatter]],?plot_width=400,?plot_height=350)

        output

        我們也可以借此多繪制幾個直方圖,然后組合起來

        #重置表格的行索引:
        df.reset_index(inplace=True)

        #創(chuàng)建水平方向的直方圖:
        p_hbar?=?df.plot_bokeh(
        ????kind="barh",
        ????x="fruits",
        ????xlabel="Price?per?Unit?[€]",
        ????title="Fruit?prices?per?Year",
        ????alpha=0.6,
        ????legend?=?"bottom_right",
        ????show_figure=False)

        #創(chuàng)建堆疊式的柱狀圖:
        p_stacked_hbar?=?df.plot_bokeh.barh(
        ????x="fruits",
        ????stacked=True,
        ????xlabel="Price?per?Unit?[€]",
        ????title="Fruit?prices?per?Year",
        ????alpha=0.6,
        ????legend?=?"bottom_right",
        ????show_figure=False)

        #Plot?all?barplot?examples?in?a?grid:
        pandas_bokeh.plot_grid([[p_bar,?p_stacked_bar],
        ????????????????????????[p_hbar,?p_stacked_hbar]],?
        ???????????????????????plot_width=450)

        output



        E?N?D

        各位伙伴們好,詹帥本帥搭建了一個個人博客和小程序,匯集各種干貨和資源,也方便大家閱讀,感興趣的小伙伴請移步小程序體驗一下哦?。g迎提建議)

        推薦閱讀


        牛逼!Python常用數(shù)據(jù)類型的基本操作(長文系列第①篇)

        牛逼!Python的判斷、循環(huán)和各種表達式(長文系列第②篇)

        牛逼!Python函數(shù)和文件操作(長文系列第③篇)

        牛逼!Python錯誤、異常和模塊(長文系列第④篇)


        瀏覽 84
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

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

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            制服丝袜在线播放 | 日本一区二区三区乱伦 | 污片网站 | 国产欧美另类五月丁香水多多 | 乱伦电影毛片 | 影音先锋乱伦电影 | 久久精品99 | 成人做爱在线观看 | 黄色片网址 | 毛片日逼 |