countplot

文章详细介绍了seaborn库中的countplot函数,用于绘制计数条形图。该方法可以基于x轴、y轴或hue参数进行数据统计,支持DataFrame输入。示例中以泰坦尼克号数据集展示了不同参数的用法,包括设置数据列、排序、颜色和定向等。
摘要由CSDN通过智能技术生成

countplot

导入seaborn库

1

import seaborn as sns

使用countplot

1

sns.countplot()

countplot方法中必须要x或者y参数,不然就报错。

官方给出的countplot方法及参数:

sns.countplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, dodge=True, ax=None, **kwargs)

下面讲解countplot方法中的每一个参数。以泰坦尼克号为例。

原始数据如下:

1

2

3

sns.set(style='darkgrid')

titanic = sns.load_dataset('titanic')

titanic.head()

x, y, hue : names of variables in ``data`` or vector data, optional. Inputs for plotting long-form data. See examples for interpretation.

第一种方式

x: x轴上的条形图,以x标签划分统计个数

y: y轴上的条形图,以y标签划分统计个数

hue: 在x或y标签划分的同时,再以hue标签划分统计个数

1

sns.countplot(x="class", data=titanic)

1

sns.countplot(y="class", data=titanic)

1

sns.countplot(x="class", hue="who", data=titanic)

第二种方法

x: x轴上的条形图,直接为series数据

y: y轴上的条形图,直接为series数据

1

sns.countplot(x=titanic['class'])

1

sns.countplot(y=titanic['class'])

data : DataFrame, array, or list of arrays, optional. Dataset for plotting.
If ``x`` and ``y`` are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form.

data: DataFrame或array或array列表,用于绘图的数据集,x或y缺失时,data参数为数据集,同时x或y不可缺少,必须要有其中一个。

1

sns.countplot(x='class', data=titanic)

order, hue_order : lists of strings, optional.Order to plot the categorical levels in, otherwise the levels are inferred from the data objects.
order, hue_order分别是对x或y的字段排序,hue的字段排序。排序的方式为列表。

1

sns.countplot(x='class', data=titanic, order=['Third', 'Second', 'First'])

1

sns.countplot(x='class', hue='who', data=titanic, hue_order=['woman', 'man', 'child'])

orient : "v" | "h", optional
Orientation of the plot (vertical or horizontal). This is usually
inferred from the dtype of the input variables, but can be used to
specify when the "categorical" variable is a numeric or when plotting
wide-form data.
强制定向,v:竖直方向;h:水平方向,具体实例未知。

color : matplotlib color, optional
Color for all of the elements, or seed for a gradient palette.

palette : palette name, list, or dict, optional.Colors to use for the different levels of the ``hue`` variable.
Should be something that can be interpreted by :func:`color_palette`, or a dictionary mapping hue levels to matplotlib colors.

palette:使用不同的调色板

1

sns.countplot(x="who", data=titanic, palette="Set3")

ax : matplotlib Axes, optional
Axes object to draw the plot onto, otherwise uses the current Axes.

ax用来指定坐标系。

1

2

3

fig, ax = plt.subplots(1, 2, figsize=(10, 5))

sns.countplot(x='class', data=titanic, ax=ax[0])

sns.countplot(y='class', data=titanic, ax=ax[1])

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值