0

I have data as follows, to which I would like to simply add a legend (blue means something, red means another thing), for some reason nothing I try even shows up:

Some posts I looked at: A, B, C

library(tidyverse)

dat <- structure(list(group_size = structure(c(
  6L, 3L, 3L, 4L, 1L, 2L,
  2L, 1L, 3L, 6L, 2L, 6L, 2L, 2L, 1L, 1L, 4L, 1L, 3L, 2L
), .Label = c(
  "(0,50]",
  "(50,100]", "(100,150]", "(150,200]", "(200,250]", "(250,3e+03]"
), class = "factor"), amount = c(
  409, 101, 103, 198, 40, 63,
  69, 49, 126, 304, 91, 401, 96, 63, 36, 1, 177, 7, 112, 61
), group_sum = c(
  1114,
  442, 442, 375, 133, 443, 443, 133, 442, 1114, 443, 1114, 443,
  443, 133, 133, 375, 133, 442, 443
), count = c(
  3L, 4L, 4L, 2L,
  5L, 6L, 6L, 5L, 4L, 3L, 6L, 3L, 6L, 6L, 5L, 5L, 2L, 5L, 4L, 6L
)), row.names = c(NA, -20L), class = c("data.table", "data.frame"))

dat %>%
  as_tibble() %>%
  ggplot(aes(x = group_size)) +
  geom_col(aes(y = group_sum), position = "identity", color = "red", fill = "transparent") +
  geom_label(
    data = dat %>% distinct(group_size, .keep_all = TRUE),
    mapping = aes(y = group_sum, label = group_sum),
    color = "red"
  ) +
  geom_col(aes(y = count * 10), position = "identity", color = "blue", fill = "transparent") +
  geom_label(
    data = dat %>% distinct(count, .keep_all = TRUE),
    mapping = aes(y = count * 10, label = count),
    color = "blue"
  ) +
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . / 10, name = "Count"))

enter image description here

Tom
  • 2,173
  • 1
  • 17
  • 44
  • Did you try mapping colour to a column in your data? Your approach sets the bars to some colour. Seems like you need to reshape your data. – markus Feb 22 '22 at 12:00

1 Answers1

2

If you want to to have a legend for the colors, you have to map it inside of aes() instead of after it in the geom_col(aes()). Afterwards, adjust to your desires using scale_color_identity.

dat %>%
  as_tibble() %>%
  ggplot(aes(x = group_size)) +
  geom_col(aes(y = group_sum, color = "red"), position = "identity", fill = "transparent") +
  geom_label(
    data = dat %>% distinct(group_size, .keep_all = TRUE),
    mapping = aes(y = group_sum, label = group_sum), color = "red") +
  geom_col(aes(y = count * 10, color = "blue"), position = "identity", fill = "transparent") +
  geom_label(
    data = dat %>% distinct(count, .keep_all = TRUE),
    mapping = aes(y = count * 10, label = count), color = "blue") +
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . / 10, name = "Count")) +
  labs(color = "Legend") +
  scale_color_identity(name = "Your Legend Name",
                       breaks = c("red", "blue"),
                       labels = c("Your red Name", "Your blue"),
                       guide = "legend")

enter image description here

Gnueghoidune
  • 1,237
  • 4
  • 13