日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

7000字 23张图,Pandas一键生成炫酷的动态交互式图表

發布時間:2024/9/15 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 7000字 23张图,Pandas一键生成炫酷的动态交互式图表 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

  • 折線圖

  • 散點圖

  • 直方圖

  • 柱狀圖

  • 餅圖

  • 面積圖

  • 地圖

  • 組合圖

準備工作

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

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

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

折線圖

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

import?numpy?as?npnp.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

繪制出來的圖表可以任意的縮放以及拖拽,我們也可以點擊右邊的“保存”按鈕來實現對圖表的下載保存,以至于圖表的類型只需要對參數kind加以設定,我們將上面的代碼優化一下

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類似,我們也可以在圖標的底部添加一個時間軸,拖動時間軸來展示數據

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

當然我們也可以對折線加以修改,就可以變成另外一種樣子,主要修改的就是參數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數據集可視化",show_figure=True, )

output

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

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

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)"]?=?20p_scatter?=?df.plot_bokeh.scatter(x="petal?length(cm)",y="sepal?width(cm)",category="species",title="Iris數據集可視化",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這個參數來實現

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參數來幫助我們更好的觀察數據的走勢

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

上面的代碼只是引用了表格當中的一列,當然我們也可以不做指定,引用表格當中的每一列數據

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="""<h2>?@{name}?</h2>?<h3>?Population:?@{pop_max}?</h3>""",tile_provider="STAMEN_TERRAIN_RETINA",size="population",?figsize=(900,?600),title="全球特大城市分布")

output

從圖中可以看出,亞洲的日本主要是集中在東京這塊,而像在國內的話,有大家熟知的北上廣深。上面的代碼有兩個參數x和y分別對應的是經緯度,

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?)?*?100slider_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

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

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="""<imgsrc="https://www.states101.com/img/flags/gif/small/@STATE_NAME_SMALL.gif"?height="42"?alt="@imgs"?width="42"style="float:?left;?margin:?0px?15px?15px?0px;"border="2"></img><h2>??@STATE_NAME?</h2><h3>?2010:?@POPESTIMATE2010?</h3><h3>?2017:?@POPESTIMATE2017?</h3>""",tile_provider_url=r"http://c.tile.stamen.com/watercolor/{Z}/{X}/{Y}.jpg",tile_attribution='Map?tiles?by?<a?href="http://stamen.com">Stamen?Design</a>,?under?<a?href="http://creativecommons.org/licenses/by/3.0">CC?BY?3.0</a>.?Data?by?<a?href="http://openstreetmap.org">OpenStreetMap</a>,?under?<a?href="http://www.openstreetmap.org/copyright">ODbL</a>.')

output

最后我們可以通過區域的篩選來進行數據的呈現,通過`category`這個參數來實現

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模塊也能夠實現多張圖表的組合,例如上面 人口密度的圖表就可以和美國各大洲的人口總量的圖表進行組合

#繪制出大致的輪廓圖 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="""<h1>@name</h1><h3>Population:?@pop_max?</h3>""",marker="inverted_triangle",legend="Cities", )

上面的代碼我們主要是用到了pandas_bokeh.plot_grid這個方法來將多個圖結合起來,再來看幾個簡單的案例

df?=?pd.read_csv("iris.csv")from?bokeh.models.widgets?import?DataTable,?TableColumn from?bokeh.models?import?ColumnDataSourcedata_table?=?DataTable(columns=[TableColumn(field=Ci,?title=Ci)?for?Ci?in?df.columns],source=ColumnDataSource(df),height=300, )#?創建散點圖: p_scatter?=?df.plot_bokeh.scatter(x="petal?length(cm)",y="sepal?width(cm)",category="species",title="Iris數據可視化",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)#創建水平方向的直方圖: 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)#創建堆疊式的柱狀圖: 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

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

推薦閱讀

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

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

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

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

總結

以上是生活随笔為你收集整理的7000字 23张图,Pandas一键生成炫酷的动态交互式图表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。