用Python进行数据可视化的10种方法

浏览: 2238

用Python进行数据可视化的10种方法

引言

艺术之美根植于其所传达的信息。有时候,现实并非我们所看到或感知到的。达芬奇(Da Vinci)和毕加索(Picasso)等艺术家都通过其具有特定主题的非凡艺术品,试图让人们更加接近现实。

数据科学家并不逊色于艺术家。他们用数据可视化的方式绘画,试图展现数据内隐藏的模式或表达对数据的见解。更有趣的是,一旦接触到任何可视化的内容、数据时,人类会有更强烈的知觉、认知和交流。

在数据科学中,有多种工具可以进行可视化。在本文中,我展示了使用Python来实现的各种可视化图表。

怎样才能在Python中实现可视化?

涉及到的东西并不多!Python已经让你很容易就能实现可视化——只需借助可视化的两个专属库(libraries),俗称matplotlib和seaborn。听说过吗?

Matplotlib:基于Python的绘图库为matplotlib提供了完整的2D和有限3D图形支持。这对在跨平台互动环境中发布高质量图片很有用。它也可用于动画。

Seaborn:Seaborn是一个Python中用于创建信息丰富和有吸引力的统计图形库。这个库是基于matplotlib的。 Seaborn提供多种功能,如内置主题、调色板、函数和工具,来实现单因素、双因素、线性回归、数据矩阵、统计时间序列等的可视化,以让我们来进一步构 建复杂的可视化。

我能做哪些不同的可视化?

刚出版不久的《A comprehensive guide on Data Visualization》中,介绍了最常用的可视化技术。在进一步深入学习前,如果你尚未阅读此书,我们建议你参考此书。

以下是Python代码与其输出结果。我就是用下面的数据集来创建这些可视化的。

导入数据集

import matplotlib.pyplot as plt
import pandas as pd
df=pd.read_excel("E:/First.xlsx",sheet1")

1.直方图

fig=plt.figure()#Plots in matplotlib reside within a figure object,use plt.figure to create new figure
#Create one or more subplots using add_subplot,because you can't create blank figure ax=fig.add_subplot(1,1,1)
#Variable
ax.hist(df['Age'],bins=7)# Here you can play with number of bins
Labels and Tit
plt.title('Age distribution')
plt.xlabel('Age')
plt.ylabel('#Employee')
plt.show()

2.箱线图

import matplotlib.pyplot as plt
import pandas as pd
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
#Vaeiable
ax.boxplot(df['Age'])
plt.show()


3.小提琴图

import seaborn as sns
sns.violinplot(df['Age'],df)#Variable Plot
sns.despine()


4.条形图

var=df.grouby('Gender').Sales.sum()#grouped sum of sales at Gender level
fig=plt.figure()
ax1=fig.add_subplot(1,1,1)
ax1.set_xlabel('Gender')
ax1.set_ylabel('Sum of Sales')
ax1.set_title("Gender wise Sum of Sales")
var.plot(kind='bar')


5.折线图

var=df.groupby('BMI').Sales.sum()
fig=plt.figure()
ax1=fig.add_subplot(1,1,1)
ax1.set_xlabel('BMI')
ax1.set_ylabel('Sum of Sales')
ax1.set_title("BMI wise Sum of Sales")
var.plot(king='line')


6.堆积柱形图

var=df.groupby(['BMI','Gender']).Sales.sum()
var.unstack().plot(kind='bar',stacked=True,color=['red','blue'],stockid=False)


7.散点图

fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.scatter(df['Age'],df['Sales'])#You can also add more variables here to represent color and size.
plt.show()


8.气泡图

fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.scatter(df['Age'],df['Sales'],s=df['Income'])#Added third variable income as size of the bubble
plt.show()


9.饼图

var=df.groupby(['Gender']).sum().stack()
temp=var.unstack()
type(temp)
x_list=temp['Sales']
label_list=temp.index
pyplot.axis("equal")#The pie chart is oval by default.To make it a circle use pyplot.axis("equal")
#To show the percentage of each pie slice,pass an output format to the autopctparameter
plt.pie(x_list,labels=list,autopct="%1.1f%%")
plt.title("Pastafatianism expenses")
plt.show()


10.热图

import numpy as np
#Generate a random munber,you can refer your data values alse
data=np.random.tand(4,2)
rows=list('1234')#rows categories
fig.ax=plt.subplots()
#Adbance color controls
ax.pcolor()data.cmap=plt.cm.Reds,edgecolors='k')
ax.set_xticks(np.arange(0,2)+0.5)
ax.set_yticks(np.arange(0,4)+0.5)
# Here we position the tick labels for x and y axis
ax.xaxis.tick_bottom()
ax.yaxis.tick_left()
#Values ahainst each labels
ax.set_xticklabels(columns,minor=False,fontsize=20)
ax.set_yticklabels(rows,minor=False,fontsize=20)
plt.show()

结语

现在,你肯定已经意识到了数据可视化的美妙,为什么不自己动手试试呢?在以后的文章中,我们还将探讨用Python实现地图可视化和词云。

推荐 4
本文由 天源清浅 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册