ggplot2

常用代码块参数(新手必学):

一些快捷键:

导入库

library(dplyr)
library(ggplot2)
library(dslabs)

use ggplot2

看下数据

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是一个初始空白画布

使用ggplot画图

aes是美观参数(aesthetic),其中带入数据,生成对应大小坐标系

p <- murders %>% ggplot(aes(x=population, y=total)) 
p

画点图geom_point()

使用p变量直接添加点图

p+geom_point()

直接使用管道一口气绘图,无需赋值,顺便给每个点附上label(aes中是告诉ggplot数据来源,geom_label才是绘制label)

murders %>% ggplot(aes(x=population,y=total,label= abb))+geom_label()

用region来区分颜色

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()

x,y取对数, 这样看起来更舒服

murders %>% ggplot(aes(x=population,y=total,label= abb, color=region))+geom_label()+scale_x_log10()+scale_y_log10()

加上横纵坐标标题和总标题(使用labs()和ggtitle() )

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')

也可用labs(label=)来替代ggtitle()
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')

直方图(用heights数据)geom_histogram()

head(heights)#
##      sex height
## 1   Male     75
## 2   Male     70
## 3   Male     68
## 4   Male     74
## 5   Male     61
## 6 Female     65

alpha代表透明度,fill代表图形内部填充色(这里用性别分类颜色)

heights %>% ggplot(aes(x=height,fill=sex,alpha=0.2))+geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value `binwidth`.

平滑密度曲线geom_density()

heights %>% ggplot(aes(x=height,fill=sex,alpha=0.2))+geom_density()

箱线图geom_boxplot()

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 ='箱线图')