- 确保系统已经安装了R
如果未安装可使用
sudo apt-get install r-base
进入R, R
安装
#直接安装tidyverse,一劳永逸(推荐,数据分析大礼包)
install.packages("tidyverse")
#直接安装ggplot2
install.packages("ggplot2")
#从Github上安装最新的版本,先安装devtools(如果没安装的话)
devtools::install_github("tidyverse/ggplot2")
4.安装tidyverse缺少依赖关系
当我尝试在deepin上安装tidyverse时,提示缺少‘httr’, ‘rvest’ 之类的依赖项。 在终端中,运行:
sudo apt-get install libcurl4-openssl-dev libssl-dev
sudo apt-get install libxml2-dev
然后重新install.packages("tidyverse")即可
- 进入 > library(tidyverse)
- 读数据
我们使用 tidyverse 中的 read_csv() 函数读取实验数据,并保存在 da 中。
> da <- read_csv('age.csv')
tidyverse 中大部分数据都是 tibble 结构,直接运行 da 就可以了。
>da
7.绘图
在图中同时呈现散点和拟合的曲线
ggplot(data = da) +
geom_point(mapping = aes(x = GDP, y = car)) +
geom_smooth(mapping = aes(x = GDP, y = car))
如果需要去掉曲线的置信区间(阴影区域), geom_smooth(mapping = aes(x = GDP, y = car), se = FALSE)
让点和曲线的颜色都根据样本名称 进行了分组:
ggplot(da, aes(age, u, color = sample)) + #图标类型 shape =sample, 可以放到color前边,只有6个类型
geom_point() +
geom_smooth(se = FALSE) +
scale_x_reverse() #坐标反转 + coord_flip()为对换坐标
8.图标类型
image.png
# Basic scatter plot
ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point(shape = 18, color = "steelblue", size = 4)
# Change point shapes and colors by groups
ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point(aes(shape = cyl, color = cyl))
# Change colors and shapes manually
ggplot(mtcars, aes(x=wt, y=mpg, group=cyl)) +
geom_point(aes(shape=cyl, color=cyl), size=2)+
scale_shape_manual(values=c(3, 16, 17))+
scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+
theme(legend.position="top")
9.运行R脚本
执行R文件的步骤:
step01: 创建R脚本,例如:age.R
step02: 创建shell脚本, 例如,
内容为:
#!/bin/bash
Rscript /home/andy/R/age.R
step03:运行.sh文件
sh ./age.R