R小tip(九) ggplot加label及分面

ggplot 加label

上次我们介绍了基础作图加label,这次介绍ggplot加标签


library(tidyverse)
#Reproducible data set
test_mtcars <- mtcars %>% group_by(cyl,am, gear) %>% summarise(mean = mean(mpg))

ggplot(test_mtcars, aes(as.factor(cyl), mean, fill=as.factor(am))) + 
  geom_bar(stat = "identity", position = "dodge") + 
  facet_grid(~gear) + 
  geom_text(aes(label = round(mean, 2)), position = position_dodge(width = 0.9), vjust = -1)

geom_text(aes(label = round(mean, 2)), position = position_dodge(width = 0.9), vjust = -1)是用于在图上加label,position是label在图上加的位置

分面

隆重介绍下facet_grid()
参考:https://blog.csdn.net/bodybo/article/details/78778774

#加载数据
library(reshape2)
head(tips)

library(ggplot2)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1)
数据结构
# 更加sex垂直方向进行分割
sp + facet_grid(sex ~ .)
# 对 sex 进行垂直分割, 对 day 进行水平分割
sp + facet_grid(sex ~ day)
#修改字号颜色
sp + facet_grid(sex ~ day) +
  theme(strip.text.x = element_text(size=8, angle=75),
        strip.text.y = element_text(size=12, face="bold"),
        strip.background = element_rect(colour="red", fill="#CCCCFF"))

也可以自定义label

labels <- c(Female = "Women", Male = "Men")
sp + facet_grid(. ~ sex, labeller=labeller(sex = labels))

你可能感兴趣的:(R小tip(九) ggplot加label及分面)