参考来源:Vitu.AI
上一篇中你已经熟悉了编程环境,接下来是时候来画个真格的折线图了
我们还是老样子在开头先设置一下
设置你的Notebook
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
print("设置完成")
选择数据集
本篇使用的数据集是著名流媒体音乐网站Spotify的每日播放次数,我们主要关心以下从2017到2018年的5首流行歌曲:
1."Shape of You", by Ed Sheeran
2."Despacito", by Luis Fonzi
3."Something Just Like This", by The Chainsmokers and Coldplay
4."HUMBLE.", by Kendrick Lamar
5."Unforgettable", by French Montana
点击这里 下载 数据集
用excel打开如下:
这里我们注意到第一个数据点是2017年1月6日,这是The Shape of You的首发日,你可以看到在全球首日被播放了12,287,078次。其他行在这一天是缺失值是因为还没发布
我们再把csv文件上传到vitu的数据集空间里
接下来我们用pandas来加载这个文件:
# Path of the file to read
spotify_filepath = "spotify.csv"
# Read the file into a variable spotify_data
spotify_data = pd.read_csv(spotify_filepath, index_col="Date", parse_dates=True)
是时候来检验一下数据了
我们接下来会打印一下数据集的前5行,和上一篇里一样
# Print the first 5 rows of the data
spotify_data.head()
可以看到和excel中打开看到的一样,第一行里都是缺失值NaN(Not a Number)
我们可以在看看最后的5行,这次只要把head改为tail。
# Print the last five rows of the data
spotify_data.tail()
终于,缺失值都没有了,我们可以来画图了
画图的环节来了
数据都在前面的cell里加载到notebook了,所以我们很容易一行代码就把图给画了
# Line chart showing daily global streams of each song
sns.lineplot(data=spotify_data)
在这一行代码里
sns.lineplot告诉notebook说我想要画一个折线图,如果sns.barplot则代表柱状图,sns.heatmap代表热力图
data=spotify_data则代表数据集我们选择的是spotify_data
有时候我们想改变一些画图的细节,比如图的大小或者设置title,这时可以这样设置
# 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)
画子数据集的数据
到目前为止我们学会了画数据集中所有列的数据,在这个环节我们将学习如何画某些列的数据
首先我们先看看所有的列:
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")