13

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

图表上的多色文本

其中引用了这个:

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()

这是结果图:

# Cylinders(mtcars 数据集)的马力与每加仑英里数的关系

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

4

2 回答 2

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()
于 2012-08-15T22:50:22.273 回答
1

将单词包装在虚拟表中的一种可能策略,

library(gridExtra)
library(grid)
library(ggplot2)
title = c('Concentration of ','affluence',' and ','poverty',' nationwide')
colors = c('black', '#EEB422','black', '#238E68','black')

grid.arrange(ggplot(), 
             top = tableGrob(t(title), 
                             theme=ttheme_minimal(padding=unit(c(0,2),'mm'),
                                                  base_colour = colors)))

在此处输入图像描述

于 2018-04-10T07:44:11.210 回答