用于R的ggplot2的多色标题

ide*_*tor 13 r ggplot2

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

图表上的多色文本

引用了这个:

R中的多色文本

这就是我提出的(在这里得到帮助):

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()
Run Code Online (Sandbox Code Playgroud)

这是结果图:

通过#Cylinders(mtcars数据集)的马力与每加仑的里程数

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

Jos*_*ien 8

这是一种更通用的方法,它利用了一些额外的网格功能.它没有特别精心打磨,但它可能会给你一些有用的想法:

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()
Run Code Online (Sandbox Code Playgroud)