R for data Science(二)

ggplot2数据可视化

这次我们接着上面的继续讲解数据可视化,数据集是mpg数据集
image
image

那我们怎么做出上面的这些图呢?这里我提供了我的代码

library(ggplot2)
ggplot(data = mpg, mapping = aes(x = displ, y = hwy, color = drv)) +
geom_point() +
geom_smooth(se = FALSE)

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth(se = FALSE)

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth(aes(group = drv), se = FALSE)

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(aes(color = drv)) +
geom_smooth(aes(group = drv,color = drv), se = FALSE)

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(aes(color = drv)) +
geom_smooth(se = FALSE)

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(aes(color = drv)) + geom_smooth(aes(linetype = drv))

这里需要注意一点,se=FALSE代表的是置信区间不显示,因为默认情况下会显示,会在图形周围形成一段阴影
ggplot2绘图原理: 就是图层的叠加,如果所有的图层共用一个数据集,那直接就可以把数据集放在ggplot后面即可,如果是每一个图层用的数据集不一样,则需要我们把数据集放进图层后面的参数里面,涂层的概念和我们在PS里面的图层是一样的概念,所呈现出来的图形就是多个图层累积的结果。

常用的几何对象:

geom_point 画点图
geom_smooth 画曲线
geom_bar 画柱形图
geom_boxplot 画箱式图
geom_abline 画直线
geom_text 添加标注

ggplot(data = diamonds) + 
 geom_bar(mapping = aes(x = cut, fill = clarity), position = "fill")</pre>
image
ggplot(data = diamonds) + 
 geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")</pre>
image
ggplot(data = diamonds) + 
geom_bar(mapping = aes(x = cut, fill = clarity), position = "identity")</pre>
image
我们可以看到三个position参数区别:
fill 显示的是每一个部分的所占比例
identity 则是直接累积
dodge 则是进行柱状图显示

坐标轴转换

bar <- ggplot(data = diamonds) + 
 geom_bar(
 mapping = aes(x = cut, fill = cut), 
 show.legend = FALSE,
 width = 1
 ) + 
 theme(aspect.ratio = 1) +
 labs(x = NULL, y = NULL)
bar
bar + coord_flip() ##横纵坐标颠倒显示
bar + coord_polar() ##极坐标

分别显示下面三张图

image
image
image
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容