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认证考试体系应 ...
2025-03-10推荐学习书籍 《CDA一级教材》在线电子版正式上线CDA网校,为你提供系统、实用、前沿的学习资源,助你轻松迈入数据分析的大门! ...
2025-03-07在数据驱动决策的时代,掌握多样的数据分析方法,就如同拥有了开启宝藏的多把钥匙,能帮助我们从海量数据中挖掘出关键信息,本 ...
2025-03-06在备考 CDA 考试的漫漫征途上,拥有一套契合考试大纲的优质模拟题库,其重要性不言而喻。它恰似黑夜里熠熠生辉的启明星,为每一 ...
2025-03-05“纲举目张,执本末从。”若想在数据分析领域有所收获,一套合适的学习教材至关重要。一套优质且契合需求的学习教材无疑是那关 ...
2025-03-04以下的文章内容来源于刘静老师的专栏,如果您想阅读专栏《10大业务分析模型突破业务瓶颈》,点击下方链接 https://edu.cda.cn/go ...
2025-03-04在现代商业环境中,数据分析师的角色愈发重要。数据分析师通过解读数据,帮助企业做出更明智的决策。因此,考取数据分析师证书成为了许多人提升职业竞争力的选择。本文将详细介绍考取数据分析师证书的过程,包括了解证书种类和 ...
2025-03-03在当今信息化社会,大数据已成为各行各业不可或缺的宝贵资源。大数据专业应运而生,旨在培养具备扎实理论基础和实践能力,能够应 ...
2025-03-03数据分析师认证考试全面升级后,除了考试场次和报名时间,小伙伴们最关心的就是报名费了,报 ...
2025-03-032025年刚开启,知乎上就出现了一个热帖: 2024年突然出现的经济下行,使各行各业都感觉到压力山大。有人说,大环境越来越不好了 ...
2025-03-03大数据分析师培训旨在培养学员掌握大数据分析的基础知识、技术及应用能力,以适应企业对数据分析人才的需求。根据不同的培训需求 ...
2025-03-03小伙伴们,最近被《哪吒2》刷屏了吧!这部电影不仅在国内掀起观影热潮,还在全球范围内引发了关注,成为中国电影崛起的又一里程 ...
2025-03-03以下的文章内容来源于张彦存老师的专栏,如果您想阅读专栏《Python 数据可视化 18 讲(PyEcharts、Matplotlib、Seaborn)》,点 ...
2025-02-28最近,国产AI模型DeepSeek爆火,其创始人梁文峰走进大众视野。《黑神话:悟空》制作人冯骥盛赞DeepSeek为“国运级别的科技成果” ...
2025-02-271.统计学简介 听说你已经被统计学劝退,被Python唬住……先别着急划走,看完这篇再说! 先说结论,大多数情况下的学不会都不是知 ...
2025-02-27“我们的利润率上升了,但销售额却没变,这是为什么?” “某个业务的市场份额在下滑,到底是什么原因?” “公司整体业绩稳定, ...
2025-02-26在数据分析工作中,你可能经常遇到这样的问题: 从浏览到消费的转化率一直很低,那到底该优化哪里呢? 如果你要投放广告该怎么 ...
2025-02-25近来deepseek爆火,看看deepseek能否帮我们快速实现数据看板实时更新。 可以看出这对不知道怎么动手的小白来说是相当友好的,尤 ...
2025-02-25挖掘用户价值本质是让企业从‘赚今天的钱’升级为‘赚未来的钱’,同时让用户从‘被推销’变为‘被满足’。询问deepseek关于挖 ...
2025-02-25在当今这个数据驱动的时代,几乎每一个业务决策都离不开对数据的深入分析。而其中,指标波动归因分析更是至关重要的一环。无论是 ...
2025-02-25