[英]Seaborn/Matplotlib categorical plot markers size by count of observations
我想通過觀察計數來縮放 2 個分類變量圖上的標記。
我使用seaborn.pairplot
為了方便,因為我有很多變量(功能)。 但我認為這樣的案例沒有任何論據。
我猜您正在尋找的是氣球圖,也稱為矩陣氣泡圖或分類氣泡圖。 據我所知,從 0.11.0 版本開始,seaborn 不提供這種類型的繪圖,因此目前不能選擇使用 pairplot。 我知道有兩個函數提供這種類型的圖,顯示單個分類到分類關系與標記大小的選定數值變量:這個在 pygal 包和catscatter 中。 但缺點是這兩者都要求您將觀察計數作為數據集中的一列,我認為這不是您的情況。
這是一種創建氣球圖的方法,該氣球圖顯示按熊貓數據框中包含的兩個分類變量分組的觀察計數:
import pandas as pd # v 1.1.3
import matplotlib.pyplot as plt # v 3.3.2
import seaborn as sns # v 0.11.0
# Import seaborn sample dataset stored as a pandas dataframe and select
# the categorical variables to plot
df = sns.load_dataset('titanic')
x = 'who' # contains 3 unique values: 'child', 'man', 'woman'
y = 'embark_town' # contains 3 unique values: 'Southampton', 'Queenstown', 'Cherbourg'
# Compute the counts of observations
df_counts = df.groupby([x, y]).size().reset_index()
df_counts.columns.values[df_counts.columns == 0] = 'count'
# Compute a size variable for the markers so that they have a good size regardless
# of the total count and the number of unique values in each categorical variable
scale = 500*df_counts['count'].size
size = df_counts['count']/df_counts['count'].sum()*scale
# Create matplotlib scatter plot with additional formatting
fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(x, y, size, data=df_counts, zorder=2)
ax.grid(color='grey', linestyle='--', alpha=0.4, zorder=1)
ax.tick_params(length=0)
ax.set_frame_on(False)
ax.margins(.3)
靈感來源: catscatter , 這個答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.