作者|Dario Radečić
编译|VK
起源|Towards Datas Science
2020年行将完结(终于),数据可视化再重要不过了。出现一个看起来像5岁小孩的货色曾经不再是一个抉择,所以数据科学家须要一个有吸引力和简略易用的数据可视化库。
明天咱们将比拟其中的两个-Matplotlib和ggplot2。
为什么是这两个?Matplotlib是我学习的第一个可视化库。但最近我越来越喜爱R语言的ggplot2了,然而明天咱们将在这两个库中从新创立五个雷同的图,看看代码和美学方面的停顿。
数据呢?咱们将应用两个驰名的数据集:mtcars和航空乘客。你能够通过导出CSV性能通过RStudio取得第一个,第二个在这里可用:https://raw.githubusercontent...
以下是R和Python的库导入:
R: library(ggplot2) Python: import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates mtcars = pd.read_csv('mtcars.csv')
直方图
咱们应用直方图来可视化给定变量的散布。这正是咱们对mtcars数据集所做的——可视化MPG属性的散布。
以下是R的代码和后果:
ggplot(mtcars, aes(x=mpg)) + geom_histogram(bins=15, fill='#087E8B', color='#02454d') + ggtitle('Histogram of MPG') + xlab('MPG') + ylab('Count')
Python也是这样:
plt.figure(figsize=(12, 7)) plt.hist(mtcars['mpg'], bins=15, color='#087E8B', ec='#02454d')plt.title('Histogram of MPG') plt.xlabel('MPG') plt.ylabel('Count');
默认状况下两者十分类似。即便咱们须要编写的代码量也大致相同,所以很难在这里抉择最喜爱的代码。我喜爱Python的x轴是从0开始的,但在R中能够很容易地扭转。另一方面,我喜爱R中没有边界,但这也是Python中易于实现的货色。
平局
条形图
条形图由不同高度的矩形组成,其中高度示意给定属性段的值。咱们将应用它们来比拟不同数量的圆柱体(属性cyl)的计数。
以下是R的代码和后果:
ggplot(mtcars, aes(x=cyl)) + geom_bar(fill='#087E8B', color='#02454d') + scale_x_continuous(breaks=seq(min(mtcars$cyl), max(mtcars$cyl), by=2)) + ggtitle('Bar chart of CYL') + xlab('Number of cylinders') + ylab('Count')
Python也是一样:
bar_x = mtcars['cyl'].value_counts().index bar_height = mtcars['cyl'].value_counts().values plt.figure(figsize=(12, 7)) plt.bar(x=bar_x, height=bar_height, color='#087E8B', ec='#02454d') plt.xticks([4, 6, 8]) plt.title('Bar chart of CYL') plt.xlabel('Number of cylinders') plt.ylabel('Count');
毫无疑问,R的代码更整洁、更简略,因为Python须要手动计算高度。从美学角度看,它们十分类似,但代码我更喜爱R版。
获胜者:ggplot2
散点图
散点图用于可视化两个变量之间的关系。这样做的目标是察看第二个变量随着第一个变量的变动(回升或降落)会产生什么。咱们还能够通过对其余属性值的点着色来为二维图增加另一个“维度”。
咱们将应用散点图来可视化HP和MPG属性之间的关系。
以下是R的代码和后果:
ggplot(mtcars, aes(x=hp, y=mpg)) + geom_point(aes(size=cyl, color=cyl)) + ggtitle('Scatter plot of HP vs MPG') + xlab('Horse power') + ylab('Miles per gallon')
Python也是一样:
colors = [] for val in mtcars['cyl']: if val == 4: colors.append('#17314c') elif val == 6: colors.append('#326b99') else: colors.append('#54aef3') plt.figure(figsize=(12, 7)) plt.scatter(x=mtcars['hp'], y=mtcars['mpg'], s=mtcars['cyl'] * 20, c=colors) plt.title('Scatter plot of HP vs MPG') plt.xlabel('Horse power') plt.ylabel('Miles per gallon');
代码方面,这是R和ggplot2的显著胜利。Matplotlib不提供一种简略的办法,通过第三个属性给数据点上色,因而咱们必须手动执行该步骤。尺寸也有点怪。
获胜者:ggplot2
箱线图
箱线图用于通过四分位数可视化数据。它们通常会有线(胡须)从盒子里伸出来,这些线在高低四分位数之外显示出变动。两头的线是中值。顶部或底部显示的点被视为异样值。
咱们将应用箱线图,通过不同的CYL值来可视化MPG。
以下是R的代码和后果:
ggplot(mtcars, aes(x=as.factor(cyl), y=mpg)) + geom_boxplot(fill='#087E8B', alpha=0.6) + ggtitle('Boxplot of CYL vs MPG') + xlab('Number of cylinders') + ylab('Miles per gallon')
Python也是一样:
boxplot_data = [ mtcars[mtcars['cyl'] == 4]['mpg'].tolist(), mtcars[mtcars['cyl'] == 6]['mpg'].tolist(), mtcars[mtcars['cyl'] == 8]['mpg'].tolist() ] fig = plt.figure(1, figsize=(12, 7)) ax = fig.add_subplot(111) bp = ax.boxplot(boxplot_data, patch_artist=True) for box in bp['boxes']: box.set(facecolor='#087E8B', alpha=0.6, linewidth=2) for whisker in bp['whiskers']: whisker.set(linewidth=2) for median in bp['medians']: median.set(color='black', linewidth=3) ax.set_title('Boxplot of CYL vs MPG') ax.set_xlabel('Number of cylinders') ax.set_ylabel('Miles per galon') ax.set_xticklabels([4, 6, 8]);
有一件事是立刻可见的-Matplotlib须要大量的代码来生成一个外观不错的boxplot。ggplot2不是这样。到目前为止,R是这里显著的赢家。
获胜者:ggplot2
折线图
当初咱们将从mtcars数据集转移到airline passengers数据集。咱们将应用它创立一个带有日期格局的x轴的简略折线图。这并不像听起来那么容易。
以下是R的代码和后果:
ap <- read.csv('https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv') ap$Month <- as.Date(paste(ap$Month, '-01', sep='')) ggplot(ap, aes(x=Month, y=Passengers)) + geom_line(size=1.5, color='#087E8B') + scale_x_date(date_breaks='1 year', date_labels='%Y') + ggtitle('Line chart of Airline passengers') + xlab('Year') + ylab('Count')
Python也是一样:
ap = pd.read_csv('https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv') ap['Month'] = ap['Month'].apply(lambda x: pd.to_datetime(f'{x}-01')) fig = plt.figure(1, figsize=(12, 7)) ax = fig.add_subplot(111) line = ax.plot(ap['Month'], ap['Passengers'], lw=2.5, color='#087E8B') formatter = mdates.DateFormatter('%Y')ax.xaxis.set_major_formatter(formatter) locator = mdates.YearLocator() ax.xaxis.set_major_locator(locator) ax.set_title('Line chart of Airline passengers') ax.set_xlabel('Year') ax.set_ylabel('Count');
从美学角度来看,这些图表简直完全相同,但在代码量方面,ggplot2再次击败Matplotlib。与Python相比,R在X轴显示日期要容易得多。
获胜者:ggplot2
论断
在我看来,ggplot2在简略性和数据可视化好看方面是一个显著的赢家。简直总是能够归结为十分类似的3-5行代码,而Python则不是这样。
原文链接:https://towardsdatascience.co...
欢送关注磐创AI博客站:
http://panchuang.net/
sklearn机器学习中文官网文档:
http://sklearn123.com/
欢送关注磐创博客资源汇总站:
http://docs.panchuang.net/