Multicolor titles with ggplot2 for R

前端 未结 2 1023
春和景丽
春和景丽 2020-12-18 22:27

I was trying to implement multicolor texts as shown here:

multicolor text on chart

which referenced this:

multicolor text in R

This is what I

2条回答
  •  失恋的感觉
    2020-12-18 22:57

    Here's a more general approach that takes advantage of a few additional grid functions. It's not particularly well-polished, but it may give you some useful ideas:

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

提交回复
热议问题