Добавление точки в легенду ggplot из другого фрейма данных - PullRequest
1 голос
/ 06 августа 2020

Я пытаюсь добавить контрольную точку к моей легенде из другого фрейма данных. В настоящее время в моей легенде показаны значения для моей первой geom_point (), но я хочу добавить точку серым цветом с меткой «Предыдущий опрос» для представления geom_point () из data2.

data1 <- data.frame(wording = paste0("my_survey_item_", 1:30),
                    survey_question = paste0('Q_', 1:30),
                    perc_favorability = rbinom(30, 100, .7)*.01)
data2 <- data.frame(wording = paste0("my_survey_item_", 1:30),
                    survey_question = paste0('Q_', 1:30),
                    perc_favorability = rbinom(30, 100, .7)*.01)

#conditional coloring
data1$trending <- ifelse(data1$survey_question %in% data2$survey_question & data1$survey_question %in% data2$survey_question &data1$perc_favorability > data2$perc_favorability, "green", ifelse(data1$survey_question %in% data2$survey_question & data1$survey_question %in% data2$survey_question & data1$perc_favorability < data2$perc_favorability, "red", "black"))




#trying to figure out how to add the grey dot to the legend
pfavorable_change <- data1 %>% 
  ggplot(aes(x = perc_favorability , y = reorder(survey_question, perc_favorability), color = trending)) + 
  geom_point(stat = "identity") + 
  scale_x_continuous(labels = scales::percent) + 
  geom_point(data = data2, color = "grey", stat = "identity") +
  geom_text(aes(x = perc_favorability, y = reorder(survey_question, perc_favorability), label = wording),
            label=data1$wording, 
            position = position_nudge(x = -0.015),
            check_overlap = T,
            inherit.aes = F,
            hjust = 1) + 
  scale_colour_manual(name = '', 
                      values =c('red'='red', 'black'='black', 'green'='green'), 
                      labels = c('Remained', 'Decreased', 'Improved'), #you might need to re-order these
                      drop=FALSE) +
  #scale_fill_manual(values = c("red", "black", "green", "gray"), 
  #                  drop = FALSE ,
  #                  name="", 
  #                  labels=c("Decreased", "Remained", "Improved") +
  coord_cartesian(xlim = c(0,1), expand = T) +
  ggtitle("Overall Favorability") +
  xlab("Favorability") + ylab("Survey Questions") + 
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5),
        axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank(),
        legend.position = c(.9,.2), 
        legend.background = element_rect(fill=alpha('white', 0.5)),
        legend.spacing.x = unit(.7, 'mm'),
        legend.text = element_text(margin = margin(t = 1.5, unit = 'mm')))
pfavorable_change  + removeGrid( x = FALSE) 

введите описание изображения здесь

1 Ответ

1 голос
/ 06 августа 2020

Есть отличный пост здесь , обсуждающий эту проблему. В вашем примере поместите color = "grey" внутри aes как aes(color = "grey") и добавьте функцию scale_color_identity, как показано ниже.

scale_color_identity(name = "Legend",
                     breaks = c("grey", "green", "red"),
                     labels = c("From previous survey", "Decreased", "Removed"),
                     guide = "legend")
...