公衆號:尤而小屋
作者:Peter
編輯:Peter
大家好,我是Peter~
很久沒有更新Plotly相關的文章,國慶這幾天終於幹了一篇。選擇的主題是:玩轉Plotly圖例設置,也是一直以來都想寫的一個話題,文章的主要內容爲:
官網學習地址:https://plotly.com/python/legend/
Plotly連載文章
Plotly文章目前已經更新到第16篇,歡迎閱讀。推薦幾篇文章:
導入庫和數據
本文中主要使用的數據是消費數據:
import pandas as pd
import numpy as np
import plotly_express as px
import plotly.graph_objects as go
# 消費數據
tips = px.data.tips()
tips.head()
圖例元素個數
主要是單個元素和多個元素組成的圖例。
單個元素
fig = px.scatter(
tips, # 數據庫
x="total_bill", # xy軸
y="tip",
color="sex" # 圖例是通過顏色區分
)
fig.show()
多個元素組成的圖例
多個元素同時區分的時候,會生成不同的形狀來進行數據的展示:
fig = px.scatter(
tips,
x="total_bill",
y="tip",
color="sex", # 顏色和標記來同時區分
symbol="smoker"
)
fig.show()
改變圖例名稱
在使用plotly_express的時候主要使用labels參數來修改圖例名稱
fig = px.scatter(
tips,
x="total_bill",
y="tip",
color="sex", # 顏色和標記;symbol主要來控制形狀
symbol="smoker",
# 通過labels來改變默認的圖例名稱
labels={"sex": "Gender", "smoker": "Smokes"})
fig.show()
還可以生成具有多個切面圖形的圖形:
fig = px.scatter(
tips,
x="total_bill",
y="tip",
color="sex",
symbol="smoker",
facet_col="time", # 切面圖的列元素
# 改變圖例名稱
labels={"sex": "Gender", "smoker": "Smokes"})
fig.show()
設置圖例順序
通過plotly_express繪圖
通過參數legend.traceorder來設置圖例的順序
fig = px.bar(
tips, # 數據框
x="day", # xy軸
y="total_bill",
color="smoker", # 顏色
barmode="stack", # 柱狀圖模式
facet_col="sex", # 切面圖的列元素
category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], # 自定義順序
"smoker": ["Yes", "No"],
"sex": ["Male", "Female"]})
fig.update_layout(legend_traceorder="reversed") # 設置順序
fig.show()
⚠️默認情況下是根據現實圖例的字段在原始數據中出現的順序:
fig = px.bar(
tips, # 數據框
x="day", # xy軸
y="total_bill",
color="smoker", # 顏色
barmode="stack", # 柱狀圖模式
facet_col="sex", # 切面圖的列元素
)
fig.show()
通過plotly.graph_objects繪圖
我們主要是通過參數 legendrank 來設置順序 。注意:plotly的版本必須在V5.0及以上
pip install --upgrade plotly # 升級版本
如果我們不使用legendrank參數:
fig = go.Figure()
# 添加4個不同的軌跡數據
fig.add_trace(go.Bar(name="first", x=["a", "b"], y=[21,27]))
fig.add_trace(go.Bar(name="second", x=["a", "b"], y=[32,18]))
fig.add_trace(go.Bar(name="third", x=["a", "b"], y=[11,32]))
fig.add_trace(go.Bar(name="fourth", x=["a", "b"], y=[21,13]))
fig.show()
上面圖例出現的順序就是first 、second、third、fourth的順序,也就是在添加軌跡數據的順序。
下面我們使用legendrank參數:
fig = go.Figure()
# 添加4個不同的軌跡數據
fig.add_trace(go.Bar(name="second", # 2
x=["a", "b"],
y=[32,18],
legendrank=2))
fig.add_trace(go.Bar(name="third", # 3
x=["a", "b"],
y=[11,32],
legendrank=3))
fig.add_trace(go.Bar(name="first", # 1
x=["a", "b"],
y=[21,27],
legendrank=1))
fig.add_trace(go.Bar(name="fourth", # 4
x=["a", "b"],
y=[21,13],
legendrank=4))
fig.show()
添加trace的順序不同是first、second等,實際上還是按照legendrank參數來排序
顯示和隱藏圖例
上面的所有圖形在默認情況下是顯示圖例出來,我們也可以來進行隱藏:
# 隱藏圖例
fig = px.scatter(
tips,
x="total_bill",
y="tip",
color="sex",
symbol="smoker"
)
fig.update_layout(showlegend=False) # 隱藏圖例元素
fig.show()
圖例位置
圖例默認情況下是在右邊的,我們可以使用參數來改變圖例位置
# 默認情況:圖例在右上角
fig = px.scatter(
tips,
x="total_bill",
y="tip",
size="tip",
color="sex", # 顏色和標記來同時區分
symbol="smoker"
)
fig.show()
通過參數的設置來改變圖例的位置:
# 默認情況
fig = px.scatter(
tips,
x="total_bill",
y="tip",
size="tip",
color="sex", # 顏色和標記來同時區分
symbol="smoker"
)
# 通過位置參數來改變
fig.update_layout(legend=dict(
yanchor="top", # y軸頂部
y=0.99,
xanchor="left", # x軸靠左
x=0.01
))
fig.show()
圖例水平化
默認情況圖例是垂直顯示,通過參數orientation來實現水平顯示。當圖例的分類情況很多的時候,這個水平化顯示非常使用。
本案例使用的plotly中的gdp數據:
默認圖例是垂直顯示:
df = px.data.gapminder().query("year==2007") # 選擇2007數據
fig = px.scatter(
df, # 數據框和x、y軸數據
x="gdpPercap",
y="lifeExp",
color="continent", # 顏色
size="pop", # 大小
size_max=45) # 最大值
fig.update_layout(legend=dict(
# orientation="h", # 控制水平顯示
yanchor="bottom", # 分別設置xy軸的位置和距離大小
y=1.02,
xanchor="right",
x=1
))
fig.show()
下面我們來開啓水平顯示圖例:
# 開啓水平顯示
fig = px.scatter(
df,
x="gdpPercap",
y="lifeExp",
color="continent",
size="pop",
size_max=45)
fig.update_layout(legend=dict(
orientation="h", # 開啓水平顯示
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
))
fig.show()
圖例個性化顯示
fig = px.scatter(
df,
x="gdpPercap",
y="lifeExp",
color="continent",
size="pop",
size_max=45
)
fig.update_layout(
legend=dict(
x=.82, # 設置圖例位置
y=0,
traceorder="reversed",
title_font_family="Times New Roman", # 圖例標題字體
font=dict( # 圖例字體
family="Courier",
size=13,
color="red" # 顏色:紅色
),
bgcolor="LightSteelBlue", # 圖例背景色
bordercolor="Black", # 圖例邊框顏色和寬度
borderwidth=2
)
)
fig.show()
Graph Objects設置圖例
下面的多個案例都是基於plotly.graph_objects來進行圖例的設置:
- 圖例名稱
圖例名稱
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[1, 2, 3, 4, 5],
y=[1, 2, 3, 4, 5],
name="圖1" # 圖例名稱
))
fig.add_trace(go.Scatter(
x=[1, 2, 3, 4, 5],
y=[5, 4, 3, 2, 1],
name="圖2" # 圖例名稱
))
fig.show()
圖例標題
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[1, 2, 3, 4, 5],
y=[1, 2, 3, 4, 5],
name="圖1"
))
fig.add_trace(go.Scatter(
x=[1, 2, 3, 4, 5],
y=[5, 4, 3, 2, 1],
name="圖2"
))
# 重點參數:設置圖例標題
fig.update_layout(legend_title_text='圖例標題')
fig.show()
顯示或隱藏圖例
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x=list(range(5)),
y=list(range(5)),
showlegend=False # 不顯示這個軌跡的圖例
))
fig.add_trace(go.Scatter(
x=list(range(5)),
y=list(range(5))[::-1],
))
fig.update_layout(showlegend=True) # 整體圖例顯示
fig.show()
設置圖例元素大小
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x=list(range(5)),
y=list(range(5)),
mode='markers+lines', # 模式的選擇
marker={'size':10} # 標記大小
))
fig.add_trace(go.Scatter(
x=list(range(5)),
y=[5, 4, 3, 2, 1],
mode='lines+markers',
marker={'size':50}
))
fig.update_layout(legend= {'itemsizing': 'constant'}) # trace 和constant兩種設置
fig.show()
當itemsizing取值爲constant:
當itemsizing取值爲trace: