R

R绘图_ggplot2分面Facet

2020-02-27  本文已影响0人  谢俊飞

ggplot2在线学习:STHDA :Statistical tools for high-throughput data analysis.
ggplot2使用说明:https://ggplot2.tidyverse.org/reference/

Facet

英文:http://www.sthda.com/english/wiki/ggplot2-facet-split-a-plot-into-a-matrix-of-panels

根据说明文档,运行代码……

#ggplot2 facet : split a plot into a matrix of panels

rm(list = ls())
library(ggplot2)

#convert the dose from numeric to factor variables
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
df <- ToothGrowth
head(df)

#basic box plot
bp <- ggplot(df, aes(x=dose, y=len, group=dose)) +
  geom_boxplot(aes(fill=dose))
bp

#facet with one variable
bp + facet_grid(supp ~ .)
bp + facet_grid(. ~ supp)

#facet with two variable
#rows are dose and columns are supp
bp + facet_grid(dose ~ supp)
#rows are supp and columns are dose
bp + facet_grid(supp ~ dose)

# we can use the argument margins to add additional facets which cotain all the data
#for each of the possible values of the faceting variables
bp + facet_grid(supp ~ dose, margins = TRUE)

#facet scales
bp + facet_grid(dose ~ supp, scales = "free")

#facet labels
bp + facet_grid(dose ~ supp, labeller = label_both)
#Possible values for the font style:'plain', 'italic', 'bold', 'bold.italic'.
bp + facet_grid(dose ~ supp) +
  theme(strip.text.x = element_text(size = 12, color = "red",face = "bold.italic"),
        strip.text.y = element_text(size = 12, colour = "red", face = "bold.italic"))

#change the apperance of the rectangle around facet label
bp + facet_grid(dose ~ supp) +
  theme(strip.background = element_rect(colour = "black", fill = "white", 
                                        size = 1.5, linetype = "solid"))
#facet wrap 
bp + facet_wrap( ~ dose)
bp + facet_wrap( ~ dose, ncol = 2)
上一篇 下一篇

猜你喜欢

热点阅读