7000字 23張圖,Pandas一鍵生成炫酷的動態(tài)交互式圖表
今天小編來演示一下如何用pandas一行代碼來繪制可以動態(tài)交互的圖表,并且將繪制的圖表組合到一起,組成可視化大屏,本次小編將要繪制的圖表有
折線圖 散點圖 直方圖 柱狀圖 餅圖 面積圖 地圖 組合圖
準備工作
我們先導(dǎo)入需要用到的庫,并做相應(yīng)的設(shè)置
import?pandas?as?pd
import?pandas_bokeh
pandas_bokeh.output_notebook()
因為小編是在jupyter nobteook上面操作的,這邊就用到了output_notebook()的設(shè)置
折線圖
我們先來畫一張簡單的折線圖,當(dāng)中隨機生成一批數(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

kind加以設(shè)定,我們將上面的代碼優(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

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

markerx?=?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ù)則是設(shè)置圖表的標題我們也可以通過當(dāng)中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

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

x和y分別對應(yīng)的是經(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())
df_states.plot_bokeh(
????figsize=(900,?600),
????category="POPESTIMATE2017",
????simplify_shapes=5000,
????colormap="Inferno",
????colormap_uselog=True,
????colorbar_tick_format="0.0a")
output

當(dāng)然我們也可以在地圖上面添加一個時間軸,讓圖表隨著時間的流逝而變化
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

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


相關(guān)閱讀:
評論
圖片
表情
