常用代码块参数(新手必学):
echo=FALSE:不显示代码,只显示运行结果(适合最终报告);
warning=FALSE:隐藏代码运行的警告信息;
message=FALSE:隐藏包加载时的普通提示(比如”载入程序包:dplyr”);
fig.width=6, fig.height=4:设置图表宽度/高度(英寸);
include=FALSE:运行代码但不显示代码和结果(适合数据预处理)。
一些快捷键:
alt + —:<-赋值
crtl+/:正常注释
crtl+shift+C:rmarkdown中加注释
crtl+shift+M:管道符号
crtl+alt+I:添加r代码块
library(dplyr)
library(ggplot2)
library(dslabs)
看下数据
head(murders)
## state abb region population total
## 1 Alabama AL South 4779736 135
## 2 Alaska AK West 710231 19
## 3 Arizona AZ West 6392017 232
## 4 Arkansas AR South 2915918 93
## 5 California CA West 37253956 1257
## 6 Colorado CO West 5029196 65
两种写法等价,管道式写法更加常用
p=ggplot(murders)
p <- murders %>% ggplot()#两种写法等价,管道式写法更加常用.crtl+shift+M:管道符号
p #p是一个初始空白画布
aes是美观参数(aesthetic),其中带入数据,生成对应大小坐标系
p <- murders %>% ggplot(aes(x=population, y=total))
p
p+geom_point()
murders %>% ggplot(aes(x=population,y=total,label= abb))+geom_label()
murders %>% ggplot(aes(x=population,y=total,label= abb))+geom_label(col='blue')
murders %>% ggplot(aes(x=population,y=total,label= abb, color=region))+geom_label()
murders %>% ggplot(aes(x=population,y=total,label= abb, color=region))+geom_label()+scale_x_log10()+scale_y_log10()
murders %>% ggplot(aes(x=population,y=total,label= abb, color=region))+
geom_label()+scale_x_log10()+scale_y_log10()+
labs(x='Population(in log-scale)',y='Total Gun Murders(in log-scale)')+
ggtitle('Gun Murders In 2002')
murders %>% ggplot(aes(x=population,y=total,label= abb, color=region))+
geom_label()+scale_x_log10()+scale_y_log10()+
labs(x='Population(in log-scale)',y='Total Gun Murders(in log-scale)',title='Gun Murders In 2002')
head(heights)#
## sex height
## 1 Male 75
## 2 Male 70
## 3 Male 68
## 4 Male 74
## 5 Male 61
## 6 Female 65
heights %>% ggplot(aes(x=height,fill=sex,alpha=0.2))+geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value `binwidth`.
heights %>% ggplot(aes(x=height,fill=sex,alpha=0.2))+geom_density()
heights %>% ggplot(aes(y=height,fill=sex,alpha=0.2))+geom_boxplot()
p <- heights %>% ggplot(aes(y=height,fill=sex,alpha=0.2))+geom_boxplot()
p+labs(title ='箱线图')