1. 导包

  1. import pandas as pd
  2. pd.plotting.register_matplotlib_converters()
  3. import matplotlib.pyplot as plt
  4. import seaborn as sns
  5. print("Setup Complete")

2. 引入文件

原始数据如下
image.png

  1. # Path of the file to read
  2. fifa_filepath = "../input/fifa.csv"
  3. # Read the file into a variable fifa_data
  4. fifa_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).
    1. # Print the first 5 rows of the data
    2. fifa_data.head()
    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

    完整代码

    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())

  1. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/1788465/1648104644561-4d51f496-2125-46eb-8b48-8c685dc8c449.png#clientId=uc6acf5f9-8e0c-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=195&id=uf4503ff5&margin=%5Bobject%20Object%5D&name=image.png&originHeight=304&originWidth=869&originalType=binary&ratio=1&rotation=0&showTitle=false&size=31702&status=done&style=none&taskId=u41ef7a49-4090-4fa2-bc06-ee82bce6eff&title=&width=556.16)<br />如果不加index那一列显示结果如下:<br />![image.png](https://cdn.nlark.com/yuque/0/2022/png/1788465/1648131712234-3960cf47-ffd7-44fc-a35e-5ce3e25a1373.png#clientId=u8a93ca5b-356e-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=116&id=u1c5243b7&margin=%5Bobject%20Object%5D&name=image.png&originHeight=181&originWidth=864&originalType=binary&ratio=1&rotation=0&showTitle=false&size=10170&status=done&style=none&taskId=u76ebc289-c3c9-4a9b-97f5-b4c629c0369&title=&width=552.96)
  2. <a name="juLqx"></a>
  3. #### 3. 绘图
  4. ```python
  5. # Set the width and height of the figure
  6. plt.figure(figsize=(16,6))
  7. # Line chart showing how FIFA rankings evolved over time
  8. sns.lineplot(data=fifa_data)
  9. plt.show()

image.png

Line Charts(折线图)

image.png

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).
image.png

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()

image.png

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()

image.png
image.png

当加上index_col后
image.png
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.
image.png

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!)

image.png

散点图(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'])

image.png

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'])

image.png
显示抽烟与否 与 bmi、charge的关系

4. 添加回归线

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

image.png

5. 散点图分类

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

image.png

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)

image.png
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)
    

    image.png

    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.
    image.png

  • 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. 读文件
    ```python

    Paths 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()

![image.png](https://cdn.nlark.com/yuque/0/2022/png/1788465/1648729884515-ec815b32-fd6d-41b4-9d7d-67412f8adb42.png#clientId=ued9cc79d-8eb6-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=223&id=u53c6da22&margin=%5Bobject%20Object%5D&name=image.png&originHeight=348&originWidth=1103&originalType=binary&ratio=1&rotation=0&showTitle=false&size=41755&status=done&style=none&taskId=u1cd88ca9-7335-458e-a2ce-a585d96824f&title=&width=705.92)
```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
image.png

# 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")

image.png

图的总结

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")

sns.countplot() 画条形图

https://www.cnblogs.com/cgmcoding/p/13355748.html