R ggplot2 facet_wrap重新排序子图并为每个ID标签设置不同的颜色 [英] R ggplot2 facet_wrap reordering subfigure and set different colors for each ID label

查看:822
本文介绍了R ggplot2 facet_wrap重新排序子图并为每个ID标签设置不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对ggplot facet_wrap中的子图顺序重新排序,并为其子图文本标签指定某种颜色.

I am trying to reorder the subfigures order in ggplot facet_wrap and specify a certain color for their subfigure text label.

这是我的数据集:

  ID <- rep(c('ABC123','DEF456','GHI789','JKL012'),each = 10)
  Vref <- c((runif(10,1,2)),(runif(10,3,5)),(runif(10,6,9)),(runif(10,0,2)))
  Time <- rep(c(1:10),4)
  df <- data.frame(ID,Vref,Time)
  ggplot(df) + geom_point(aes(x=Time, y=Vref)) + facet_wrap(~ID, nrow = 2)

现在,子图的顺序为ABC123-> DEF456-> GHI789-> JKL012. 所有文本标签均为黑色.

Now the order of subfigure is ABC123 --> DEF456 --> GHI789 --> JKL012. All text labels are in black.

我的问题是:

如何将订单更改为GHI789-> ABC123-> JKL012-> DEF456? 如何指定红色,绿色,黄色和蓝色的颜色?

How to change the order to GHI789 --> ABC123 --> JKL012 --> DEF456 ? How to specify the color in red, green, yellow, and blue ?

谢谢.

推荐答案

为条形文本指定颜色的一种方法是使用grid包中的编辑功能.通常grid.ls()和其他编辑功能只能看到一个grob,但是grid.force()会使ggplot中的所有grob对网格的编辑功能可见.

One approach to specifying colours for the strip texts is to use editing functions from the grid package. Usually grid.ls() and other editing functions see just one grob, but grid.force() makes all the grobs in the ggplot visible to grid's editing functions.

library(grid)
library(ggplot2)

ID <- rep(c('ABC123','DEF456','GHI789','JKL012'),each = 10)
Vref <- c((runif(10,1,2)),(runif(10,3,5)),(runif(10,6,9)),(runif(10,0,2)))
Time <- rep(c(1:10),4)
df <- data.frame(ID,Vref,Time)

# Change order of strip texts
df$ID = factor(df$ID, levels = c("GHI789", "ABC123", "JKL012", "DEF456"))

p = ggplot(df) + geom_point(aes(x=Time, y=Vref)) + facet_wrap(~ID, nrow = 2) 

gp <- ggplotGrob(p)  # Get ggplot grob

# Get the names of the grobs
# grid.force makes all the grobs visible to grid's editing functions
names.grobs <- grid.ls(grid.force(gp))$name

# Inspect the list. The required grobs' names begin with GRID.text,
# but so do other text grobs - to do with the axes.
# Therefore, in the edit, use gPath to limit the editing to GRID.text in the strip,
# and not the GRID.text in the axes.

strip.text <- names.grobs[which(grepl("GRID.text", names.grobs))]

# Set up the colours
colour <- c("yellow", "blue", "red", "green")

# The edit
for(i in 1:4) gp = editGrob(grid.force(gp), 
                     gPath("GRID.titleGrob", strip.text[i]), 
                     grep = TRUE,    
                     gp = gpar(col = colour[i]))

# Draw it 
grid.newpage()
grid.draw(gp)

这篇关于R ggplot2 facet_wrap重新排序子图并为每个ID标签设置不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆