Python数据可视化的完整版操作指南

数据集

    我们将使用temporal数据集来适应本文中显示的可视化效果,数据集可通过下方链接进行下载。

数据集:https://github.com/albertsl/datasets/tree/master/popularidad

Pandas

在介绍更复杂的方法之前,让我们从可视化数据的最基本方法开始。我们将只使用熊猫来查看数据并了解其分布方式。

我们要做的第一件事是可视化一些示例,查看这些示例包含了哪些列、哪些信息以及如何对值进行编码等等。

import pandas as pddf = pd.read_csv('temporal.csv')df.head(10) 
Mesdata sciencemachine learningdeep learning
02004-01-0112184
12004-02-0112212
22004-03-019212
32004-04-0110164
42004-05-017143
52004-06-019173
62004-07-019163
72004-08-017143
82004-09-0110174
92004-10-018174

使用命令描述,我们将看到数据如何分布,最大值,最小值,均值……

df.describe()
data sciencemachine learningdeep learning
count194.000000194.000000194.000000
mean20.95360827.39690724.231959
std23.95100628.09149034.476887
min4.0000007.0000001.000000
25%6.0000009.0000002.000000
50%8.00000013.0000003.000000
75%26.75000031.50000034.000000
max100.000000100.000000100.000000

使用info命令,我们将看到每列包含的数据类型。我们可以发现一列的情况,当使用head命令查看时,该列似乎是数字的,但是如果我们查看后续数据,则字符串格式的值将被编码为字符串。

df.info()
<class 'pandas.core.frame.DataFrame'>RangeIndex: 194 entries, 0 to 193Data columns (total 4 columns):Mes 194 non-null objectdata science 194 non-null int64machine learning 194 non-null int64deep learning 194 non-null int64dtypes: int64(3), object(1)memory usage: 6.2+ KB

通常情况下,pandas都会限制其显示的行数和列数。这可能让很多程序员感到困扰,因为大家都希望能够可视化所有数据。

使用这些命令,我们可以增加限制,并且可以可视化整个数据。对于大型数据集,请谨慎使用此选项,否则可能无法显示它们。

pd.set_option('display.max_rows',500)pd.set_option('display.max_columns',500)pd.set_option('display.width',1000)

使用Pandas样式,我们可以在查看表格时获得更多信息。首先,我们定义一个格式字典,以便以清晰的方式显示数字(以一定格式显示一定数量的小数、日期和小时,并使用百分比、货币等)。不要惊慌,这是仅显示而不会更改数据,以后再处理也不会有任何问题。

为了给出每种类型的示例,我添加了货币和百分比符号,即使它们对于此数据没有任何意义。

format_dict = {'data science':'${0:,.2f}', 'Mes':'{:%m-%Y}', 'machine learning':'{:.2%}'}#We make sure that the Month column has datetime formatdf['Mes'] = pd.to_datetime(df['Mes'])#We apply the style to the visualizationdf.head().style.format(format_dict)
Mesdata sciencemachine learningdeep learning
001-2004$12.001800.00%4
102-2004$12.002100.00%2
203-2004$9.002100.00%2
304-2004$10.001600.00%4
405-2004$7.001400.00%3

我们可以用颜色突出显示最大值和最小值。

format_dict = {'Mes':'{:%m-%Y}'} #Simplified format dictionary with values that do make sense for our datadf.head().style.format(format_dict).highlight_max(color='darkgreen').highlight_min(color='#ff0000')

我们使用颜色渐变来显示数据值。

df.head(10).style.format(format_dict).background_gradient(subset=['data science', 'machine learning'], cmap='BuGn')

我们也可以用条形显示数据值。

df.head().style.format(format_dict).bar(color='red', subset=['data science', 'deep learning'])

此外,我们还可以结合以上功能并生成更复杂的可视化效果。

df.head(10).style.format(format_dict).background_gradient(subset = ['data science','machine learning'],cmap ='BuGn').highlight_max(color ='yellow')

Pandas分析

Pandas分析是一个库,可使用我们的数据生成交互式报告,我们可以看到数据的分布,数据的类型以及可能出现的问题。它非常易于使用,只需三行,我们就可以生成一个报告,该报告可以发送给任何人,即使您不了解编程也可以使用。

Matplotlib

Matplotlib是用于以图形方式可视化数据的最基本的库。它包含许多我们可以想到的图形。仅仅因为它是基本的并不意味着它并不强大,我们将要讨论的许多其他数据可视化库都基于它。

Matplotlib的图表由两个主要部分组成,即轴(界定图表区域的线)和图形(我们在其中绘制轴,标题和来自轴区域的东西),现在让我们创建最简单的图:

import matplotlib.pyplot as pltplt.plot(df['Mes'], df['data science'], label='data science') #The parameter label is to indicate the legend. This doesn't mean that it will be shown, we'll have to use another command that I'll explain later.
[<matplotlib.lines.Line2D at 0x11e3002d0>]

我们可以在同一张图中制作多个变量的图,然后进行比较。

plt.plot(df ['Mes'],df ['data science'],label ='data science')plt.plot(df ['Mes'],df ['machine learning'],label ='machine learning ')plt.plot(df ['Mes'],df ['deep learning'],label ='deep learning')

每种颜色代表哪个变量还不是很清楚。我们将通过添加图例和标题来改进图表。

plt.plot(df['Mes'], df['data science'], label='data science')plt.plot(df['Mes'], df['machine learning'], label='machine learning')plt.plot(df['Mes'], df['deep learning'], label='deep learning')plt.xlabel('Date')plt.ylabel('Popularity')plt.title('Popularity of AI terms by date')plt.grid(True)plt.legend()

如果您是从终端或脚本中使用Python,则在使用我们上面编写的函数定义图后,请使用plt.show()。如果您使用的是Jupyter Notebook,则在制作图表之前,将%matplotlib内联添加到文件的开头并运行它。

我们可以在一个图形中制作多个图形。这对于比较图表或通过单个图像轻松共享几种图表类型的数据非常有用。

fig, axes = plt.subplots(2,2)axes[0, 0].hist(df['data science'])axes[0, 1].scatter(df['Mes'], df['data science'])axes[1, 0].plot(df['Mes'], df['machine learning'])axes[1, 1].plot(df['Mes'], df['deep learning'])

我们可以为每个变量的点绘制具有不同样式的图形:

plt.plot(df ['Mes'],df ['data science'],'r-')plt.plot(df ['Mes'],df ['data science'] * 2,'bs')plt.plot(df ['Mes'],df ['data science'] * 3,'g ^')

现在让我们看一些使用Matplotlib可以做的不同图形的例子。我们从散点图开始:

plt.scatter(df['data science'], df['machine learning'])

条形图示例:

plt.bar(df ['Mes'],df ['machine learning'],width = 20)

直方图示例:

plt.hist(df ['deep learning'],bins = 15)

我们可以在图形中添加文本,并以与图形中看到的相同的单位指示文本的位置。在文本中,我们甚至可以按照TeX语言添加特殊字符

我们还可以添加指向图形上特定点的标记。

plt.plot(df['Mes'], df['data science'], label='data science')plt.plot(df['Mes'], df['machine learning'], label='machine learning')plt.plot(df['Mes'], df['deep learning'], label='deep learning')plt.xlabel('Date')plt.ylabel('Popularity')plt.title('Popularity of AI terms by date')plt.grid(True)plt.text(x='2010-01-01', y=80, s=r'$lambda=1, r^2=0.8$') #Coordinates use the same units as the graphplt.annotate('Notice something?', xy=('2014-01-01', 30), xytext=('2006-01-01', 50), arrowprops={'facecolor':'red', 'shrink':0.05})

Seaborn

Seaborn是基于Matplotlib的库。基本上,它提供给我们的是更好的图形和功能,只需一行代码即可制作复杂类型的图形。

我们导入库并使用sns.set()初始化图形样式,如果没有此命令,图形将仍然具有与Matplotlib相同的样式。我们显示了最简单的图形之一,散点图:

import seaborn as snssns.set()sns.scatterplot(df['Mes'], df['data science'])

我们可以在同一张图中添加两个以上变量的信息。为此,我们使用颜色和大小。我们还根据类别列的值制作了一个不同的图:

sns.relplot(x='Mes', y='deep learning', hue='data science', size='machine learning', data=df)

Seaborn提供的最受欢迎的图形之一是热图。通常使用它来显示数据集中变量之间的所有相关性:

sns.heatmap(df.corr(), annot = True, fmt ='.2f')

另一个最受欢迎的是配对图,它向我们显示了所有变量之间的关系。如果您有一个大数据集,请谨慎使用此功能,因为它必须显示所有数据点的次数与有列的次数相同,这意味着通过增加数据的维数,处理时间将成倍增加。

sns.pairplot(df)

联合图是一个非常有用的图,它使我们可以查看散点图以及两个变量的直方图,并查看它们的分布方式:

sns.jointplot(x='data science', y='machine learning', data=df)

登入/注册
卧槽~你还有脸回来
没有账号? 忘记密码?