Only display specific labels of a ggplot legend

2019-06-03 02:32发布

问题:

I have some data points, and I want to single out some of the points in my visualization. I would do it like this:

df = data.frame(
  x = 1:4, y = 1:4,
  special = c('normal', 'normal', 'normal', 'special')
)

ggplot(df) +
  geom_point(aes(x, y, color = special)) +
  scale_color_manual(values = c('red', 'black')) +
  labs(color = "") +
  theme_bw()

My issue here is that the black points are very self explanatory and don't need a label. I want just the red "special" label to appear. Is there a way I can hide the "normal" label?

回答1:

If you are open to having any color other than red:

ggplot(df) +
    geom_point(aes(x, y, color = special)) + scale_size(guide = "none") + 
    scale_color_discrete(breaks="special") + labs(color = "") +
    theme_bw()

EDIT :

cols <- c("normal" = "black","special" = "red")
gg <- ggplot(df) + geom_point(aes(x, y, color = special)) + labs(color = "") + theme_bw()
gg + scale_colour_manual(values = cols, limits = "special")



标签: r ggplot2 legend