Adding facet titles and changing legend title in ggplot2

后端 未结 1 849
南方客
南方客 2021-01-12 08:43

I wonder how to add facet titles in ggplot2

ggplot(diamonds, aes(cut)) + geom_bar() +   facet_grid(color ~ clarity)

and change the legend t

1条回答
  •  孤城傲影
    2021-01-12 09:31

    The facets are labeled using the levels of the factor used. So if you simply change the levels , such as

    levels(diamonds$clarity) <- letters[1:8]
    

    those facets will now be labeled using those letters. The legend title matches the label for that aesthetic mapping, which you can set via:

    + labs(fill = "Fill legend label")
    

    As an extra tidbit, I've noticed that I can set the x and y axis labels to NULL in labs but not the legend titles; for those you use an empty character if you want no title.

    Edit

    Given your clarifications, you can add text outside the plotting area using grid.text:

    print(qplot(1,1),vp = viewport(width = 0.9))
    grid.text(unit(0.95,"npc"),0.5,label = "Right label", rot = 270)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题