我试图实现多色文本,如下所示:

multicolor text on chart

其中引用了这个:

multicolor text in R

这就是我想出的(在 here 的帮助下):

require(ggplot2)
require(grid)
png(file="multicolortitle.png",width=800,height=500)
qplot(x = hp,y = mpg,data = mtcars,color=factor(mtcars$cyl),size=2) +
  scale_colour_manual(values = c("red3","green3","blue3")) +
  theme_bw() +
  opts(title = " \n ") +
  opts(legend.position = "none")
spacing  <- 20
grid.text(0.5, unit(1,"npc") - unit(1,"line"),
          label=paste("4 cylinder,",paste(rep(" ",spacing*2), collapse='')),
          gp=gpar(col="red3", fontsize=16,fontface="bold"))
grid.text(0.5, unit(1,"npc") - unit(1,"line"),
          label=paste(paste(rep(" ",spacing), collapse=''),"6 cylinder,",
            paste(rep(" ",spacing), collapse='')),
          gp=gpar(col="green3", fontsize=16,fontface="bold"))
grid.text(0.5, unit(1,"npc") - unit(1,"line"),
          label=paste(paste(rep(" ",spacing*2), collapse=''),"8 cylinder"),
          gp=gpar(col="blue3", fontsize=16,fontface="bold"))
grid.text(0.5, unit(1,"npc") - unit(2,"line"),
          label=paste(paste(rep(" ",spacing*0), collapse=''),
            "- Horsepower versus Miles per Gallon"),
          gp=gpar(col="black", fontsize=16,fontface="bold"))
dev.off()

这是结果图:

r - 带有 ggplot2 for R 的多色标题-LMLPHP

所以,我的问题是:有没有更优雅的方法来使用这个?例如,我希望能够使用 ggsave,为此创建间距是一个高度手动的过程 - 不适合我需要自动制作数百个这种性质的图的场景。我可以看到在此之上编写一些函数,但也许有更好的方法来实现与基本绘图函数一起使用的方法?

最佳答案

这是一种更通用的方法,它利用了一些额外的 网格 函数。它不是特别完善,但它可能会给你一些有用的想法:

library(grid)
library(ggplot2)

p <- ggplot(data=mtcars, aes(mpg,hp,color=factor(cyl),size=2)) +
       geom_point() + theme_bw() +
       opts(title = " \n ") + opts(legend.position="none")

## Get factor levels
levs <- levels(factor(mtcars$cyl))
n <- length(levs)

## Get factors' plotting colors
g <- ggplot_build(p)
d <- unique(g$data[[1]][c("colour", "group")])
cols <- d$colour[order(d$group)]

## Use widest label's width to determine spacing
labs <- paste(levs, "cylinder")
xlocs <- unit(0.5, "npc") +
         1.1 * (seq_len(n) - mean(seq_len(n))) * max(unit(1, "strwidth", labs))

## Plot labels in top 10% of device
pushViewport(viewport(y=0.95, height=0.1))
    grid.text(paste(levs, "cylinder"),
              x = xlocs, y=unit(0.5, "lines"),
              gp = gpar(col=cols, fontface="bold"))
    grid.text("- Horsepower versus Miles per Gallon",
              y = unit(-0.5, "lines"))
upViewport()

## Plot main figure in bottom 90% of device
pushViewport(viewport(y=0.45, height=0.9))
    print(p, newpage=FALSE)
upViewport()

关于r - 带有 ggplot2 for R 的多色标题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11976590/

10-12 17:34