【Kaggle 教程】Data Visualization

Exercise: Line Charts: 折线图

引包 seaborn

import pandas as pd
pd.plotting.register_matplotlib_converters()
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
print("Setup Complete")

Step 1: Load the data

# Path of the file to read
museum_filepath = "../input/museum_visitors.csv"

# Fill in the line below to read the file into a variable museum_data
museum_data = pd.read_csv(museum_filepath, index_col="Date", parse_dates=True)

Step 2: Review the data

# Print the last five rows of the data 
museum_data.head() #  查看前5行
museum_data.tail() # Your code here

Step 3: 画图

# Line chart showing the number of visitors to each museum over time
# Set the width and height of the figure
plt.figure(figsize=(12,6))
# Line chart showing the number of visitors to each museum over time
sns.lineplot(data=museum_data)
# Add title
plt.title("Monthly Visitors to Los Angeles City Museums")

在这里插入图片描述

# Line plot showing the number of visitors to Avila Adobe over time
# Set the width and height of the figure
plt.figure(figsize=(12,6))
# Add title
plt.title("Monthly Visitors to Avila Adobe")
# Line chart showing the number of visitors to Avila Adobe over time
sns.lineplot(data=museum_data['Avila Adobe'])
# Add label for horizontal axis
plt.xlabel("Date")

在这里插入图片描述

Bar Charts and Heatmaps: 条形图和热力图

Select a dataset
在这里插入图片描述

Load the data

# Path of the file to read
flight_filepath = "../input/flight_delays.csv"

# Read the file into a variable flight_data
flight_data = pd.read_csv(flight_filepath, index_col="Month")

Examine the data

扫描二维码关注公众号,回复: 14176731 查看本文章
flight_data

在这里插入图片描述

Bar chart

# Set the width and height of the figure
plt.figure(figsize=(10,6))

# Add title
plt.title("Average Arrival Delay for Spirit Airlines Flights, by Month")

# Bar chart showing average arrival delay for Spirit Airlines flights by month
sns.barplot(x=flight_data.index, y=flight_data['NK'])

# Add label for vertical axis
plt.ylabel("Arrival delay (in minutes)")

在这里插入图片描述

Heatmap

# Set the width and height of the figure
plt.figure(figsize=(14,7))

# Add title
plt.title("Average Arrival Delay for Each Airline, by Month")

# Heatmap showing average arrival delay for each airline by month
sns.heatmap(data=flight_data, annot=True)

# Add label for horizontal axis
plt.xlabel("Airline")

在这里插入图片描述

Scatter Plots: 散点图

Load and examine the data

# Path of the file to read
insurance_filepath = "../input/insurance.csv"

# Read the file into a variable insurance_data
insurance_data = pd.read_csv(insurance_filepath)
insurance_data.head()

在这里插入图片描述
Scatter plots

sns.scatterplot(x=insurance_data['bmi'], y=insurance_data['charges'])

在这里插入图片描述
上面的散点图表明,体重指数 (BMI) 和保险费用呈正相关,BMI 较高的客户通常也倾向于支付更多的保险费用。 (这种模式是有道理的,因为高 BMI 通常与更高的慢性病风险相关。)

要仔细检查这种关系的强度,您可能需要添加一条回归线,或者最适合数据的线。我们通过将命令更改为 sns.regplot 来做到这一点

sns.regplot(x=insurance_data['bmi'], y=insurance_data['charges'])

在这里插入图片描述
Color-coded scatter plots
我们可以使用散点图来显示(不是两个,而是……)三个变量之间的关系!一种方法是对点进行颜色编码。
例如,要了解吸烟如何影响 BMI 和保险成本之间的关系,我们可以用“吸烟者”对点进行颜色编码,并在轴上绘制其他两列(“bmi”、“charges”)。

sns.scatterplot(x=insurance_data['bmi'], y=insurance_data['charges'], hue=insurance_data['smoker'])

在这里插入图片描述
该散点图显示,虽然不吸烟者往往会随着 BMI 的增加而支付稍多的费用,但吸烟者支付的费用要高得多。
为了进一步强调这一事实,我们可以使用 sns.lmplot 命令添加两条回归线,分别对应吸烟者和非吸烟者。 (您会注意到,相对于非吸烟者的回归线,吸烟者的回归线的斜率要陡峭得多!)

sns.lmplot(x="bmi", y="charges", hue="smoker", data=insurance_data)

在这里插入图片描述
上面的 sns.lmplot 命令的工作方式与您目前所了解的命令略有不同:
我们没有设置 x=insurance_data[‘bmi’] 来选择 insurance_data 中的 ‘bmi’ 列,而是设置 x=“bmi” 来仅指定列的名称。
同样,y=“charges” 和 hue=“smoker” 也包含列的名称。
我们用 data=insurance_data 指定数据集。

最后,您将了解另外一个情节,它可能看起来与您习惯查看散点图的方式略有不同。通常,我们使用散点图来突出显示两个连续变量(如“bmi”和“charges”)之间的关系。但是,我们可以调整散点图的设计以在其中一个主轴上显示分类变量(如“吸烟者”)。我们将此绘图类型称为分类散点图,并使用 sns.swarmplot 命令构建它。

sns.swarmplot(x=insurance_data['smoker'],
              y=insurance_data['charges'])

在这里插入图片描述
除其他外,该图向我们展示了:
平均而言,非吸烟者的收费低于吸烟者,并且
支付最多的顾客是吸烟者;而支付最少的顾客是非吸烟者。

Distributions: 直方图Histograms 和 密度图 Density plots - KDE

Load and examine the data

# Path of the file to read
iris_filepath = "../input/iris.csv"

# Read the file into a variable iris_data
iris_data = pd.read_csv(iris_filepath, index_col="Id")

# Print the first 5 rows of the data
iris_data.head()

在这里插入图片描述
Histograms

# Histogram 
sns.histplot(iris_data['Petal Length (cm)'])

在这里插入图片描述
Density plots
下一种图是核密度估计 (KDE) 图。如果您不熟悉 KDE 图,可以将其视为平滑直方图。

要制作 KDE 图,我们使用 sns.kdeplot 命令。设置 shade=True 为曲线下方的区域着色(并且 data= 选择我们想要绘制的列)。

# KDE plot 
sns.kdeplot(data=iris_data['Petal Length (cm)'], shade=True)

在这里插入图片描述
2D KDE plots
创建 KDE 图时,我们不限于单列。我们可以使用 sns.jointplot 命令创建二维 (2D) KDE 图。
在下图中,颜色编码向我们展示了我们看到萼片宽度和花瓣长度的不同组合的可能性有多大,图中较暗的部分更有可能。

# 2D KDE plot
sns.jointplot(x=iris_data['Petal Length (cm)'], y=iris_data['Sepal Width (cm)'], kind="kde")

在这里插入图片描述
请注意,除了中心的 2D KDE 图,
图顶部的曲线是 x 轴上数据的 KDE 图(在本例中为 iris_data[‘Petal Length (cm)’]),并且
图右侧的曲线是 y 轴上数据的 KDE 图(在本例中为 iris_data[‘Sepal Width (cm)’])。

Color-coded plots: 颜色编码图

# Histograms for each species
sns.histplot(data=iris_data, x='Petal Length (cm)', hue='Species')

# Add title
plt.title("Histogram of Petal Lengths, by Species")

在这里插入图片描述
我们还可以使用 sns.kdeplot(如上)为每个物种创建一个 KDE 图。 data、x 和 hue 的功能与我们上面使用 sns.histplot 时的功能相同。此外,我们设置 shade=True 为每条曲线下方的区域着色。

# KDE plots for each species
sns.kdeplot(data=iris_data, x='Petal Length (cm)', hue='Species', shade=True)

# Add title
plt.title("Distribution of Petal Lengths, by Species")

在这里插入图片描述

在图中可以看到一个有趣的模式是植物似乎属于两个组中的一个,其中 Iris versicolor 和 Iris virginica 的花瓣长度似乎具有相似的值,而 Iris setosa 则完全属于一个类别。
事实上,根据这个数据集,我们甚至可以通过观察花瓣长度将任何鸢尾植物分类为 Iris setosa(与 Iris versicolor 或 Iris virginica 相对):如果鸢尾花的花瓣长度小于2厘米,最有可能是鸢尾花!

Choosing Plot Types and Custom Styles

What have you learned?
在这里插入图片描述

  • Trends - A trend is defined as a pattern of change.

    • sns.lineplot - 折线图最好显示一段时间内的趋势,多条线可用于显示多个组的趋势
  • 关系 - 您可以使用许多不同的图表类型来了解数据中变量之间的关系。

    • sns.barplot - 条形图可用于比较不同组对应的数量。
    • sns.heatmap - 热图可用于在数字表中查找颜色编码模式。
    • sns.scatterplot - 散点图显示两个连续变量之间的关系;如果用颜色编码,我们还可以显示与第三个分类变量的关系。
    • sns.regplot - 在散点图中包含一条回归线可以更容易地查看两个变量之间的任何线性关系。
    • sns.lmplot - 如果散点图包含多个颜色编码的组,此命令可用于绘制多条回归线。
    • sns.swarmplot - 分类散点图显示连续变量和分类变量之间的关系。
  • 分布 - 我们可视化分布以显示我们可以期望在变量中看到的可能值,以及它们的可能性

    • sns.histplot - 直方图显示单个数值变量的分布。
    • sns.kdeplot - KDE 图(或 2D KDE 图)显示单个数值变量(或两个数值变量)的估计平滑分布。
    • sns.jointplot - 此命令对于同时显示 2D KDE 图和每个单独变量的相应 KDE 图很有用。
# Change the style of the figure to the "dark" theme
sns.set_style("dark")

猜你喜欢

转载自blog.csdn.net/weixin_43154149/article/details/124954806