R语言基础
今天学习的主要内容是R语言基础,主要是学习R 作图的基础,参考了生信星球《R数据科学--详解ggplot2》一文。让我们开始今天的学习吧!R 语言搞起!
一、mpg数据框
mpg是ggplot2的内置数据框。我个人认为这些内置的数据都是供我们初学者来练习代码以及熟悉操作的。
既然是ggplot2的内置的,那我们首先加载ggplot2这个R包。然后查看mpg的数据类型,行列情况。我们发现mpg的数据类型为data.frame,即数据框。它是由234行和11列组成的。
library(ggplot2)
p <- mpg
class(p)
[1] "tbl_df" "tbl" "data.frame"
View(p)
如何查询每列的非重复值及每个值的重复次数呢:用dplyr包的distinct函数。
library(dplyr)
distinct(p,manufacturer) #manufacturer替换为其他列名。仅显示非重复值,不显示重复次数。
count(p,manufacturer) #显示出现次数
二、入门级绘图模板
ggplot(data =) +
(mapping = aes())
三、图形映射属性
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
黑白不好看,上色!!!
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, color = class))
大小设置
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, size = class))
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, size = class, color = class))
透明度和形状
# 将车型class映射给透明度
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, alpha = class, color = class))
# 将车型class映射给形状
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, shape = class, color = class))
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy), color = "blue")
stroke-轮廓更改
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, stroke = 3,color = class),shape=21)
三、图像分面
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow = 2) #分两行展示
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ cyl)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(. ~ cyl)
四、几何对象,j简单理解就是不同图的类型
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy))
#分组
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy, group = drv))
#隐式分组-线型
ggplot(data = mpg) +
geom_smooth(
mapping = aes(x = displ, y = hwy, linetype = drv),
)
#隐式分组-颜色
ggplot(data = mpg) +
geom_smooth(
mapping = aes(x = displ, y = hwy, color = drv),
show.legend = FALSE #不显示图例
)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
geom_smooth(mapping = aes(x = displ, y = hwy))
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth()
结语
跟着花花姐的教程来学习,真的棒!保姆级教程,步步理解,对于我这小白很友善呀!