京公网安备 11010802034615号
经营许可证编号:京B2-20210330
sns.reset_defaults()
sns.set(
rc={'figure.figsize':(7,5)},
style="white" # nicer layout )
如前所述,我非常喜欢分布。 直方图和核密度分布都是可视化特定变量的关键特征的有效方法。 让我们看看如何在一个图表中为单个变量或多个变量分配生成分布。
Left chart: Histogram and kernel density estimation of “Life Ladder” for Asian countries in 2018; Ri
每当我想直观地探索两个或多个变量之间的关系时,通常都会归结为某种形式的散点图和分布评估。 概念上相似的图有三种变体。 在每个图中,中心图(散点图,双变量KDE和hexbin)有助于理解两个变量之间的联合频率分布。 此外,在中心图的右边界和上边界,描绘了各个变量的边际单变量分布(作为KDE或直方图)。
sns.jointplot( x='Log GDP per capita', y='Life Ladder', data=data, kind='scatter' # or 'kde' or 'hex' )
Seaborn jointplot with scatter, bivariate kde, and hexbin in the center graph and marginal distribut
散点图是一种可视化两个变量的联合密度分布的方法。 我们可以通过添加色相来添加第三个变量,并通过添加size参数来可视化第四个变量。
sns.scatterplot( x='Log GDP per capita', y='Life Ladder', data=data[data['Year'] == 2018], hue='Continent', size='Gapminder Population' ) # both, hue and size are optional sns.despine() # prettier layout
Log GDP per capita against Life Ladder, colors based on the continent and size on population
小提琴图是箱形图和籽粒密度估计值的组合。 它起着箱形图的作用。 它显示了跨类别变量的定量数据分布,以便可以比较那些分布。
sns.set(
rc={'figure.figsize':(18,6)},
style="white" )
sns.violinplot(
x='Continent',
y='Life Ladder',
hue='Mean Log GDP per capita',
data=data
)
sns.despine()
Violin plot where we plot continents against Life Ladder, we use the Mean Log GDP per capita to grou
Seaborn对图在一个大网格中绘制了两个变量散点图的所有组合。 我通常感觉这有点信息过载,但是它可以帮助发现模式。
sns.set( style="white", palette="muted", color_codes=True ) sns.pairplot( data[data.Year == 2018][[ 'Life Ladder','Log GDP per capita', 'Social support','Healthy life expectancy at birth', 'Freedom to make life choices','Generosity', 'Perceptions of corruption', 'Positive affect', 'Negative affect','Confidence in national government', 'Mean Log GDP per capita' ]].dropna(), hue='Mean Log GDP per capita' )
Seaborn scatterplot grid where all selected variables a scattered against every other variable in th
对我而言,Seaborn的FacetGrid是使用Seaborn的最令人信服的论点之一,因为它使创建多图变得轻而易举。 通过对图,我们已经看到了FacetGrid的示例。 FacetGrid允许创建按变量分段的多个图表。 例如,行可以是一个变量(人均GDP类别),列可以是另一个变量(大陆)。
它确实比我个人需要更多的自定义(即使用matplotlib),但这仍然很吸引人。
FacetGrid —折线图
g = sns.FacetGrid( data.groupby(['Mean Log GDP per capita','Year','Continent'])['Life Ladder'].mean().reset_index(), row='Mean Log GDP per capita', col='Continent', margin_titles=True ) g = (g.map(plt.plot, 'Year','Life Ladder'))
Life Ladder on the Y-axis, Year on the X-axis. The grid’s columns are the continent, and the grid’s rows are the different levels of Mean Log GDP per capita. Overall things seem to be getting better for the countries with a Low Mean Log GDP per Capita in North America and the countries with a Medium or High Mean Log GDP per Capita in Europe
FacetGrid —直方图
g = sns.FacetGrid(data, col="Continent", col_wrap=3,height=4) g = (g.map(plt.hist, "Life Ladder",bins=np.arange(2,9,0.5)))
FacetGrid with a histogram of LifeLadder by continent
FacetGrid —带注释的KDE图
也可以向网格中的每个图表添加构面特定的符号。 在下面的示例中,我们添加平均值和标准偏差,并在该平均值处绘制一条垂直线(下面的代码)。
Life Ladder kernel density estimation based on the continent, annotated with a mean and standard deviation
def vertical_mean_line(x, **kwargs):
plt.axvline(x.mean(), linestyle ="--",
color = kwargs.get("color", "r"))
txkw = dict(size=15, color = kwargs.get("color", "r"))
label_x_pos_adjustment = 0.08 # this needs customization based on your data
label_y_pos_adjustment = 5 # this needs customization based on your data
if x.mean() < 6: # this needs customization based on your data
tx = "mean: {:.2f}\n(std: {:.2f})".format(x.mean(),x.std())
plt.text(x.mean() + label_x_pos_adjustment, label_y_pos_adjustment, tx, **txkw)
else:
tx = "mean: {:.2f}\n (std: {:.2f})".format(x.mean(),x.std())
plt.text(x.mean() -1.4, label_y_pos_adjustment, tx, **txkw)
_ = data.groupby(['Continent','Year'])['Life Ladder'].mean().reset_index()
g = sns.FacetGrid(_, col="Continent", height=4, aspect=0.9, col_wrap=3, margin_titles=True)
g.map(sns.kdeplot, "Life Ladder", shade=True, color='royalblue')
g.map(vertical_mean_line, "Life Ladder")
FacetGrid —热图
我最喜欢的绘图类型之一是热图FacetGrid,即网格每个面中的热图。 这种类型的绘图对于在一个绘图中可视化四个维度和一个度量很有用。 该代码有点麻烦,但可以根据需要快速进行调整。 值得注意的是,这种图表需要相对大量的数据或适当的细分,因为它不能很好地处理缺失值。
Facet heatmap, visualizing on the outer rows a year range, outer columns the GDP per Capita, on the inner rows the level of perceived corruption and the inner columns the continents. We see that happiness increases towards the top right (i.e., high GDP per Capita and low perceived corruption). The effect of time is not definite, and some continents (Europe and North America) seem to be happier than others (Africa).
def draw_heatmap(data,inner_row, inner_col, outer_row, outer_col, values, vmin,vmax):
sns.set(font_scale=1)
fg = sns.FacetGrid(
data,
row=outer_row,
col=outer_col,
margin_titles=True
)
position = left, bottom, width, height = 1.4, .2, .1, .6
cbar_ax = fg.fig.add_axes(position)
fg.map_dataframe(
draw_heatmap_facet,
x_col=inner_col,
y_col=inner_row,
values=values,
cbar_ax=cbar_ax,
vmin=vmin,
vmax=vmax
)
fg.fig.subplots_adjust(right=1.3)
plt.show()
def draw_heatmap_facet(*args, **kwargs):
data = kwargs.pop('data')
x_col = kwargs.pop('x_col')
y_col = kwargs.pop('y_col')
values = kwargs.pop('values')
d = data.pivot(index=y_col, columns=x_col, values=values)
annot = round(d,4).values
cmap = sns.color_palette("Blues",30) + sns.color_palette("Blues",30)[0::2]
#cmap = sns.color_palette("Blues",30)
sns.heatmap(
d,
**kwargs,
annot=annot,
center=0,
cmap=cmap,
linewidth=.5
)
# Data preparation
_ = data.copy()
_['Year'] = pd.cut(_['Year'],bins=[2006,2008,2012,2018])
_['GDP per Capita'] = _.groupby(['Continent','Year'])['Log GDP per capita'].transform(
pd.qcut,
q=3,
labels=(['Low','Medium','High'])
).fillna('Low')
_['Corruption'] = _.groupby(['Continent','GDP per Capita'])['Perceptions of corruption'].transform(
pd.qcut,
q=3,
labels=(['Low','Medium','High'])
)
_ = _[_['Continent'] != 'Oceania'].groupby(['Year','Continent','GDP per Capita','Corruption'])['Life Ladder'].mean().reset_index()
_['Life Ladder'] = _['Life Ladder'].fillna(-10)
draw_heatmap(
data=_,
outer_row='Corruption',
outer_col='GDP per Capita',
inner_row='Year',
inner_col='Continent',
values='Life Ladder',
vmin=3,
vmax=8,
)
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
CDA数据分析师 出品 作者:李诗怡 1. IF:基础条件判断(最常用) 作用:根据指定条件的真(TRUE)或假(FALSE),返回两种不同 ...
2026-10-30“不限专业可以考的证书”这个搜索词背后,通常藏着一个很实际的担心:专业不对口,想考个证拓宽出路,但怕报了名才发现有专业限 ...
2026-10-30先回答:能考的多是技能实操类证书 40岁、初中学历,能报的证书主要集中在四类:职业技能等级证书、专项职业能力证书、特种作业 ...
2026-10-3030岁考什么证好找工作,没有一张“通用答案”。同样的证书,对有行业经验的人和准备跨行的人,价值完全不同。更实际的思路是:先 ...
2026-10-30“专业职业技术资格证书”并不是一个正式名称,而是把好几种证书混在一起的口语说法。有人用它指会计、经济这类职称考试,有人指 ...
2026-10-30大学生能考的证书,大致分四类:通用基础类、职业资格类、专业技术资格类、岗位技能与行业认证类。真正要解决的问题不是“还有哪 ...
2026-10-30“需要考哪些证书”这个问题,没有统一答案。因为“需要”至少分三种:有的证书是入职准入,没有它连岗位门槛都进不去;有的证书 ...
2026-10-30“现在什么证含金量高好考一些”,这个问题里其实藏着两个容易打架的条件。含金量高的证书,往往有报考门槛、考试周期长;好考的 ...
2026-10-30“现在考什么证最吃香”,这个问题本身藏着一个容易踩的坑:不同人说“吃香”,指的往往不是同一件事。有人指考的人多、话题热; ...
2026-10-30文凭低,不等于没证可考,但选择空间确实窄一些。学历门槛明确的准入类资格,比如部分教师资格、法律职业资格、执业医师等,通常 ...
2026-10-30土建专业的大学生问“考什么证”,最容易踩的坑是把注册类证书当成在校目标。注册建造师、注册造价工程师、注册结构工程师、监理 ...
2026-10-30中年男人考证书,最怕两件事:一是年龄、学历卡在报名门槛外,白准备半年;二是考完发现岗位用不上,钱和时间都打了水漂。所以顺 ...
2026-10-30大专学历能考的证书不少,但真正值得投入时间的,是先确认“能不能报”,再看“考了对应什么岗位”。很多证书的报考条件里写着本 ...
2026-10-30“十大建议考的证书”这个问题,很难有一份对所有人都成立的名单。同一张证书,对会计专业大三学生、想转行做数据分析的运营、以 ...
2026-10-30“什么证书有用含金量高”这个问题,很难用一张榜单回答。同一本证书,对想进医院的人可能是硬门槛,对做运营的人却用不上;对已 ...
2026-10-30在职成年人问“考什么证书有用”,先要弄清自己需要哪一种“有用”。同一张证书,对想进入准入行业的人、想在本岗晋升的人、想转 ...
2026-10-30“女生能考的证书”真正要先回答的是“你现在的条件能报什么”。学历、专业、工作年限、是否在校、所在地区政策,直接决定你能不 ...
2026-10-30“女孩考什么证书比较好”这句话里,“比较好”其实藏着三种完全不同的标准:好考,看的是报考门槛低、备考周期短;好就业,看的 ...
2026-10-30先给结论:市场岗位没有一张通吃的证书。品牌传播、数字营销与投放、用户增长、用户研究、营销数据分析,这五条路径对应的工作任 ...
2026-10-30经济学专业考什么证书,没有统一答案。经济学毕业后去向很散:有人进银行、证券、基金,有人做财务审计,有人转数据分析与经营分 ...
2026-10-30