1. 导包
import pandas as pdpd.plotting.register_matplotlib_converters()import matplotlib.pyplot as pltimport seaborn as snsprint("Setup Complete")
2. 引入文件
原始数据如下
# Path of the file to readfifa_filepath = "../input/fifa.csv"# Read the file into a variable fifa_datafifa_data = pd.read_csv(fifa_filepath, index_col="Date", parse_dates=True)
- fifa_filepath - The filepath for the dataset always needs to be provided first.
- index_col=”Date” - When we load the dataset, we want each entry in the first column to denote a different row. To do this, we set the value of index_col to the name of the first column (“Date”, found in cell A1 of the file when it’s opened in Excel).
- parse_dates=True - This tells the notebook to understand the each row label as a date (as opposed to a number or other text with a different meaning).
We can also take a look at the last five rows of the data by making only one small change (where .head() becomes .tail()): ```python# Print the first 5 rows of the datafifa_data.head()
完整代码
import pandas as pd pd.plotting.register_matplotlib_converters() import matplotlib.pyplot as plt import seaborn as sns
fifa_filepath = “./input/fifa.csv”
Read the file into a variable fifa_data
fifa_data = pd.read_csv(fifa_filepath, index_col=”Date”, parse_dates=True) print(fifa_data.head())
<br />如果不加index那一列显示结果如下:<br /><a name="juLqx"></a>#### 3. 绘图```python# Set the width and height of the figureplt.figure(figsize=(16,6))# Line chart showing how FIFA rankings evolved over timesns.lineplot(data=fifa_data)plt.show()
Line Charts(折线图)
1. 绘制line线函数
# Line chart showing daily global streams of each song
sns.lineplot(data=spotify_data)
2. 图表的尺寸和title
Sometimes there are additional details we’d like to modify, like the size of the figure and the title of the chart. Each of these options can easily be set with a single line of code.
# Set the width and height of the figure
plt.figure(figsize=(14,6))
# Add title
plt.title("Daily Global Streams of Popular Songs in 2017-2018")
# Line chart showing daily global streams of each song
sns.lineplot(data=spotify_data)
The first line of code sets the size of the figure to 14 inches (in width) by 6 inches (in height).
3. Plot a subset of the data(绘制指定列)
# 获取所有的列
list(spotify_data.columns)
绘制前两列
# Set the width and height of the figure
plt.figure(figsize=(14,6))
# Add title
plt.title("Daily Global Streams of Popular Songs in 2017-2018")
# Line chart showing daily global streams of 'Shape of You'
sns.lineplot(data=spotify_data['Shape of You'], label="Shape of You")
# Line chart showing daily global streams of 'Despacito'
sns.lineplot(data=spotify_data['Despacito'], label="Despacito")
# Add label for horizontal axis
plt.xlabel("Date")
plt.show()
Bar图
1. 绘制bar图
import pandas as pd
pd.plotting.register_matplotlib_converters()
import matplotlib.pyplot as plt
import seaborn as sns
# 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)
# flight_data = pd.read_csv(flight_filepath, index_col="Month")
# 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'])
print(flight_data.head())
# Add label for vertical axis
plt.ylabel("Arrival delay (in minutes)")
plt.show()


当加上index_col后
Important Note: You must select the indexing column with flight_data.index, and it is not possible to use flight_data[‘Month’] (which will return an error). This is because when we loaded the dataset, the “Month” column was used to index the rows.
2. heatmaps
# 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")
- annot=True - This ensures that the values for each cell appear on the chart. (Leaving this out removes the numbers from each of the cells!)
散点图(Scatter Plots)
1. 绘制
# Read the file into a variable insurance_data
insurance_data = pd.read_csv(insurance_filepath)
sns.scatterplot(x=insurance_data['bmi'], y=insurance_data['charges'])
2. 添加回归线
sns.regplot(x=insurance_data['bmi'], y=insurance_data['charges'])
2. Color-coded scatter plots
We can use scatter plots to display the relationships between (not two, but…) three variables! One way of doing this is by color-coding the points.
For instance, to understand how smoking affects the relationship between BMI and insurance costs, we can color-code the points by ‘smoker’, and plot the other two columns (‘bmi’, ‘charges’) on the axes.
sns.scatterplot(x=insurance_data['bmi'], y=insurance_data['charges'], hue=insurance_data['smoker'])
4. 添加回归线
sns.lmplot(x="bmi", y="charges", hue="smoker", data=insurance_data)
5. 散点图分类
sns.swarmplot(x=insurance_data['smoker'],
y=insurance_data['charges'])
histograms and density plots
https://www.kaggle.com/code/alexisbcook/distributions
1. 加载数据
# 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()
2. 绘制直方图histogram
# Histogram
sns.distplot(a=iris_data['Petal Length (cm)'], kde=False)

We customize the behavior of the command with two additional pieces of information:
- a= chooses the column we’d like to plot (in this case, we chose ‘Petal Length (cm)’).
kde=False is something we’ll always provide when creating a histogram, as leaving it out will create a slightly different plot.
3. 绘制density图 (KDE) plot
# KDE plot sns.kdeplot(data=iris_data['Petal Length (cm)'], shade=True)4. 2D KDE plots
# 2D KDE plot sns.jointplot(x=iris_data['Petal Length (cm)'], y=iris_data['Sepal Width (cm)'], kind="kde")In the plot below, the color-coding shows us how likely we are to see different combinations of sepal width and petal length, where darker parts of the figure are more likely.

the curve at the top of the figure is a KDE plot for the data on the x-axis (in this case, iris_data[‘Petal Length (cm)’]), and
- the curve on the right of the figure is a KDE plot for the data on the y-axis (in this case, iris_data[‘Sepal Width (cm)’]).
Color-coded plots
1. 读文件
```pythonPaths of the files to read
iris_set_filepath = “../input/iris_setosa.csv” iris_ver_filepath = “../input/iris_versicolor.csv” iris_vir_filepath = “../input/iris_virginica.csv”
Read the files into variables
iris_set_data = pd.read_csv(iris_set_filepath, index_col=”Id”) iris_ver_data = pd.read_csv(iris_ver_filepath, index_col=”Id”) iris_vir_data = pd.read_csv(iris_vir_filepath, index_col=”Id”)
Print the first 5 rows of the Iris versicolor data
iris_ver_data.head()

```python
# Histograms for each species
sns.distplot(a=iris_set_data['Petal Length (cm)'], label="Iris-setosa", kde=False)
sns.distplot(a=iris_ver_data['Petal Length (cm)'], label="Iris-versicolor", kde=False)
sns.distplot(a=iris_vir_data['Petal Length (cm)'], label="Iris-virginica", kde=False)
# Add title
plt.title("Histogram of Petal Lengths, by Species")
# Force legend to appear,使用plt.legend( )使上述代码产生效果
plt.legend()
plt.legend()讲解https://zhuanlan.zhihu.com/p/111108841
# KDE plots for each species
sns.kdeplot(data=iris_set_data['Petal Length (cm)'], label="Iris-setosa", shade=True)
sns.kdeplot(data=iris_ver_data['Petal Length (cm)'], label="Iris-versicolor", shade=True)
sns.kdeplot(data=iris_vir_data['Petal Length (cm)'], label="Iris-virginica", shade=True)
# Add title
plt.title("Distribution of Petal Lengths, by Species")
图的总结
Since it’s not always easy to decide how to best tell the story behind your data, we’ve broken the chart types into three broad categories to help with this.
- Trends - A trend is defined as a pattern of change.
- sns.lineplot - Line charts are best to show trends over a period of time, and multiple lines can be used to show trends in more than one group.
- Relationship - There are many different chart types that you can use to understand relationships between variables in your data.
- sns.barplot - Bar charts are useful for comparing quantities corresponding to different groups.
- sns.heatmap - Heatmaps can be used to find color-coded patterns in tables of numbers.
- sns.scatterplot - Scatter plots show the relationship between two continuous variables; if color-coded, we can also show the relationship with a third categorical variable.
- sns.regplot - Including a regression line in the scatter plot makes it easier to see any linear relationship between two variables.
- sns.lmplot - This command is useful for drawing multiple regression lines, if the scatter plot contains multiple, color-coded groups.
- sns.swarmplot - Categorical scatter plots show the relationship between a continuous variable and a categorical variable.
- Distribution - We visualize distributions to show the possible values that we can expect to see in a variable, along with how likely they are.
- sns.distplot - Histograms show the distribution of a single numerical variable.
- sns.kdeplot - KDE plots (or 2D KDE plots) show an estimated, smooth distribution of a single numerical variable (or two numerical variables).
- sns.jointplot - This command is useful for simultaneously displaying a 2D KDE plot with the corresponding KDE plots for each individual variable.
Choosing Plot Types and Custom Styles
1. 改变背景风格
# Change the style of the figure to the "dark" theme
sns.set_style("dark")

