數據分析作圖神器---plotly_express

Plotly Express 入門之路

Plotly Express 是一個新的高級 Python 可視化庫:它是 Plotly.py 的高級封裝,它爲複雜的圖表提供了一個簡單的語法。 

受 Seaborn 和 ggplot2 的啓發,它專門設計爲具有簡潔,一致且易於學習的 API :只需一次導入,您就可以在一個函數調用中創建豐富的交互式繪圖,包括分面繪圖(faceting)、地圖、動畫和趨勢線。 它帶有數據集、顏色面板和主題,就像 Plotly.py 一樣。

Plotly Express 完全免費:憑藉其寬鬆的開源 MIT 許可證,您可以隨意使用它(是的,甚至在商業產品中!)。 

最重要的是,Plotly Express 與 Plotly 生態系統的其他部分完全兼容:在您的 Dash 應用程序中使用它,使用 Orca 將您的數據導出爲幾乎任何文件格式,或使用JupyterLab 圖表編輯器在 GUI 中編輯它們!

用 pip install plotly_express 命令可以安裝 Plotly Express。

使用 Plotly Express 輕鬆地進行數據可視化

一旦導入Plotly Express(通常是 px ),大多數繪圖只需要一個函數調用,接受一個整潔的Pandas dataframe,並簡單描述你想要製作的圖。 如果你想要一個基本的散點圖,它只是 px.scatter(data,x =“column_name”,y =“column_name”)

以下是 內置的 Gapminder 數據集 的示例,顯示2007年按國家/地區的人均預期壽命和人均GDP 之間的趨勢:

import plotly_express as px
gapminder = px.data.gapminder()
gapmindeer2007 = gapminder.query('year == 2007')
px.scatter(gapmindeer2007, x='gdpPercap', y='lifeExp')

如果你想通過大陸區分它們,你可以使用 color 參數爲你的點着色,由 px 負責設置默認顏色,設置圖例等:

px.scatter(gapmindeer2007, x='gdpPercap', y='lifeExp', color='continent')

這裏的每一點都是一個國家,所以也許我們想要按國家人口來衡量這些點...... 沒問題:這裏也有一個參數來設置,它被稱爲 size

px.scatter(gapmindeer2007, x= 'gdpPercap', y='lifeExp', color='continent', size='pop', size_max=60)

如果你好奇哪個國家對應哪個點? 可以添加一個 hover_name ,您可以輕鬆識別任何一點:只需將鼠標放在您感興趣的點上即可! 事實上,即使沒有 hover_name ,整個圖表也是互動的:

# 添加 facet_col 參數
px.scatter(gapminder2007, x='gdpPercap', y='lifeExp', 
           color='continent', size='pop', 
           size_max=60, hover_name='country',
          facet_col='continent')

 

也可以通過 facet_col =”continent“ 來輕鬆劃分各大洲,就像着色點一樣容易,並且讓我們使用 x軸 對數(log_x)以便在我們在圖表中看的更清晰:

# 添加 facet_col 參數
px.scatter(gapminder2007, x='gdpPercap', y='lifeExp', 
           color='continent', size='pop', 
           size_max=60, hover_name='country',
          facet_col='continent')

# 添加 facet_col 參數 和 log_x 參數
px.scatter(gapminder2007, x='gdpPercap', y='lifeExp', 
           color='continent', size='pop', 
           size_max=60, hover_name='country',
          facet_col='continent', log_x=True)

 

也許你不僅僅對 2007年 感興趣,而且你想看看這張圖表是如何隨着時間的推移而演變的。 可以通過設置 animation_frame=“year” (以及 animation_group =“country” 來標識哪些圓與控制條中的年份匹配)來設置動畫。 

在這個最終版本中,讓我們在這裏調整一些顯示,因爲像“gdpPercap” 這樣的文本有點難看,即使它是我們的數據框列的名稱。 我們可以提供更漂亮的“標籤” (labels),可以在整個圖表、圖例、標題軸和懸停(hovers)中應用。 我們還可以手動設置邊界,以便動畫在整個過程中看起來更棒:

px.scatter(gapminder, x='gdpPercap', y='lifeExp', 
           color='continent', size='pop', 
           size_max=60, hover_name='country',
          animation_frame='year', animation_group='country',
          log_x=True, range_x=[10,100000],
          range_y=[25,90], labels=dict(pop='Population', gdpPercap='GDP per Capita', lifeExp='Life Expectancy'))

因爲這是地理數據,我們也可以將其表示爲動畫地圖,因此這清楚地表明 Plotly Express 不僅僅可以繪製散點圖(不過這個數據集缺少前蘇聯的數據)。

px.choropleth(gapminder, locations='iso_alpha', color='lifeExp',
             hover_name='country', animation_frame='year',
             color_continuous_scale=px.colors.sequential.Plasma,
             projection='natural earth')

事實上,Plotly Express 支持三維散點圖、三維線形圖、極座標和地圖上三元座標以及二維座標。 條形圖(Bar)有二維笛卡爾和極座標風格。

進行可視化時,您可以使用單變量設置中的直方圖(histograms)和箱形圖(box)或小提琴圖(violin plots),或雙變量分佈的密度等高線圖(density contours)。 大多數二維笛卡爾圖接受連續或分類數據,並自動處理日期/時間數據。 可以查看我們的圖庫 (ref-3) 來了解每個圖表的例子。

 

iris = px.data.iris()
px.scatter(iris, x='sepal_width', y='sepal_length', 
           color='species', marginal_y='histogram',
          marginal_x='box', trendline='ols')

 

tips = px.data.tips()

px.scatter(tips, x='total_bill', y='tip',facet_row='time',
          facet_col='day',color='smoker',trendline='ols',
          category_orders={'day':['Thur', 'Fri', 'Sat', 'Sun'], 'time':['Lunch', 'Dinner']})

px.parallel_coordinates(iris, color='species_id',
                       color_continuous_scale=px.colors.diverging.Tealrose,
                       color_continuous_midpoint=2)

px.parallel_categories(tips, color="size", color_continuous_scale=px.colors.sequential.Inferno)

 

px.density_contour(iris, x="sepal_width", y="sepal_length")

 

px.density_contour(iris, x="sepal_width", y="sepal_length", color="species")

px.histogram(tips, x="total_bill", color="smoker", facet_row="day", facet_col="time")

px.box(tips, y="tip", x="sex", color="smoker", facet_col="day", facet_row="time", 
       category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]})

px.violin(tips, y="tip", x="sex", color="smoker", facet_col="day", facet_row="time",
         category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]})

election = px.data.election()

px.scatter_ternary(election, a="Joly", b="Coderre", c="Bergeron", color="winner", size="total", hover_name="district",
                   symbol="result", 
                   size_max=15, color_discrete_map = {"Joly": "blue", "Bergeron": "green", "Coderre":"red"}

 

px.scatter_3d(election, x="Joly", y="Coderre", z="Bergeron", color="winner", size="total", hover_name="district",
                  symbol="result", color_discrete_map = {"Joly": "blue", "Bergeron": "green", "Coderre":"red"})

 

wind = px.data.wind()

px.line_polar(wind, r="value", theta="direction", color="strength", line_close=True,
            color_discrete_sequence=px.colors.sequential.Plotly[-2::-1])

 

px.scatter_matrix(iris, dimensions=["sepal_width", "sepal_length", "petal_width", "petal_length"], color="species")

# 平行座標的顯示 跟原文一樣,暫時不知道是哪個地方的差異 (備註:Python數據之道)
px.parallel_coordinates(iris, color='species_id', color_continuous_scale=['red','green', 'blue'])

用plotly調整

import plotly_express as px

fig = px.scatter(px.data.iris(), x='sepal_width', y='sepal_length', color='species')

import plotly.graph_objs as go

fig.update(layout=dict(legend=dict(orientation='h',y=1.1,x=0.5),
                      annotations=[go.layout.Annotation(text='this one is interesting', x=3.6, y=7.2)]))

 

px.bar_polar(wind, r="value", theta="direction", color="strength", template="plotly_dark",
            color_discrete_sequence= px.colors.sequential.Plotly[-2::-1])

 

以上就是plotly_express 的應用示例,主要內容參考:這裏

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章