TiF
TiF

Reputation: 625

Lollipop chart with multiple groupings: how to remove and alter legends?

The below lollipop chart is made using ggplot2. I usefacet_wrap to get small multiples, one per group. I use geom_point to color the dots differently so to highlight differences across a second way of grouping. I hence get two legends: one made with 'facet_wrap' (groups A-C) and one made with 'geom_point' ('fruit', 'meat', 'vegetables').

How can I remove the legend made with facet_wrap, but keep the other? And how can we alter the title of the remaining one?

This question seems not to help with a legend produced by facet_wrap.

library(dplyr)
library(ggplot2)
library(tidyr)
library(plyr)

# create sample data
group <- c("A","A", "A", "A", "A", "A", "A", "A", "A","B","B","B","B", "B", "B", "B","B","B","C","C","C","C","C","C","C","C","C")
keycol <- c("var1a", "var1b","var1c", "var2a", "var2b","var3a","var3b","var3c","var3d","var1a", "var1b","var1c", "var2a", "var2b","var3a","var3b","var3c","var3d","var1a", "var1b","var1c", "var2a", "var2b","var3a","var3b","var3c","var3d")
valuecol <-c(0,0.1,0.4,0.6,0.4,0.7,0.2,0.7,0.1,0,1,0.6,0.2,0.5,0,0.3,0.4,0.1,0,0.8,0.5,0.3,0.6,0.2,0.3,0.4,0.1)

mydata <- data.frame(group, keycol, valuecol)

# create the lollipop plot

p <- ggplot(mydata, aes(y = keycol, x = valuecol, fill = group)) +
  geom_segment(aes(x = 0, y = keycol, xend = valuecol, yend = keycol), color = "grey50") +
  geom_point(aes(color=ifelse(keycol %in% c("var2a","var2b"), "fruit",
                              ifelse(keycol %in% c("var1a","var1b", "var1c"), "meat", "vegetables"))), size = 3) +
  theme(axis.title.x = element_blank(),axis.title.y = element_blank(),legend.position = "bottom") +
  facet_wrap(~group)
p

Comparing Multiple Points of Information

  1. I would like to remove the legend on the groups A-C; information is redundant.
  2. I would like to change the title of the color legend.

Any help is much appreciated. Thanks!

Upvotes: 1

Views: 1920

Answers (1)

r2evans
r2evans

Reputation: 160687

The title is fairly direct, choose from among:

p +
  scale_color_discrete(guide="none")

no legend

p +
  scale_color_discrete(name = "New Name")

new legend title

... and to remove the last, realize that it is just another scale (fill), so we remove it in the same fashion:

p +
  scale_color_discrete(name = "New Name") +
  scale_fill_discrete(guide = "none")

third plot

Upvotes: 3

Related Questions