r - How to add two titles for a wrapped legend in ggplo2? -


i add 1 title per row in wrapped legend of ggplot2 chart.

something this:

enter image description here

the code i'm using generate legend:

library(ggplot2) df <- data.frame(x=letters[1:6], y=rnorm(6, mean=10, sd=1)) p <- ggplot(df, aes(x=x, y=y, fill=x)) +      geom_bar(stat="identity") +      scale_fill_manual(         values=c('#a6cee3','#1f78b4','#b2df8a','#33a02c','#a94774','#941751','#ffd479','#bead01'),         name="",         labels=c("1", "2", "3", "4", '5', '6', '7', '8'),         guide=guide_legend(nrow=2, byrow=t, title='')      ) +      theme(legend.position='bottom') p 

thanks!

add theme(legend.position='bottom') move legend bottom.

use guide_legend(nrow=2, byrow=t, title='row 1\nrow 2' make legend wrap 2 lines , add "row 1" on top followed "row 2" underneath. lines rather close if add legend.title=element_text(lineheight=unit(1.5, 'lines')) theme space them better (sorry, not know if 1.5 value work time or whether have pick manually, did).

here's (trivial) reproducible example (love colours way - must earmark them future use!):

library(ggplot2) library(grid) # `unit` df <- data.frame(x=letters[1:6], y=rnorm(6, mean=10, sd=1)) p <- ggplot(df, aes(x=x, y=y, fill=x)) + geom_bar(stat="identity") +        scale_fill_manual(          values=c('#a6cee3','#1f78b4','#b2df8a','#33a02c','#a94774','#941751','#ffd479','#bead01'),          name="",          labels=c("1", "2", "3", "4", '5', '6', '7', '8'),          guide=guide_legend(nrow=2, byrow=t, title='row 1\nrow 2')        ) +        theme(          legend.position='bottom',          legend.title=element_text(lineheight=unit(1.5, 'lines'))        ) p 

enter image description here


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -