R ggplot 图例具有意外输出

R ggplot Legend having unexpected output

我正在绘制一些 COVID 数据的 R 图,绘制中国随时间推移的病例数与其他国家/地区的累计病例数。我还添加了一些垂直线来标记一些事件。我在传说中遇到了很多麻烦。 我希望能够显示 2 个选项: 选项 1: a) 国家案例的传说(中国 vs 其他) b) 标记事件的图例显示垂直线。

选项 2: 只是国家案例的图例(中国 vs 其他)并依靠标签显示垂直线信息。

然而,我的情节图例显示的是在一个块中同时显示国家信息和垂直线信息(见下文):

我的代码如下:

library(readr)
library(ggplot2)
library(dplyr)
library(tidyr)
library(ggrepel)
devtools::install_github("RamiKrispin/coronavirus")


library(coronavirus)
update_dataset()    

summary_china <- coronavirus %>% 
  filter(type == "confirmed" & country == "China") %>%
  group_by(date) %>% summarise(total_cases = sum(cases)) %>% mutate(country = "China") %>%
  arrange(date) 

summary_not_china <- coronavirus %>% 
  filter(type == "confirmed" & country != "China") %>%
  group_by(date) %>% summarise(total_cases = sum(cases)) %>% mutate(country = "Others") %>%
  arrange(date) 

summary_by_cases <- rbind(summary_china, summary_not_china)

#confirmed cases China vs. the rest of the world
plot_companrison <- summary_by_cases %>% ggplot(show.legend = FALSE) +
  geom_line(aes(x=date,y=total_cases, color=country), show.legend = TRUE) +
  ylab("Cumulative confirmed cases")

who_events <- tribble(
  ~ date, ~ event,
  "2020-01-30", "Global health\nemergency declared",
  "2020-03-11", "Pandemic\ndeclared",
  "2020-02-13", "China reporting\nchange"
) %>%
  mutate(date = as.Date(date))


plot_companrison + 
  geom_vline( aes(xintercept = date,  color=event),  data=who_events, show.legend = FALSE) +
  geom_label_repel(aes(x=date, label=event, color=event), data=who_events, y=2e5, force=200, show.legend = FALSE) 
 
  

我如何从国家图例中删除事件,或者有 2 个单独的图例,一个用于事件,一个用于国家? TIA

试试这个方法。但有必要提一下,@aosmith 的推荐是获得你想要的东西的最实用方法(我测试过并且工作完美。这让她成为一个非常酷和聪明的女士,当我要发布那个时,她比我秒了解决方案)。这里有一个类似的方法,但使用 annotate():

首先是数据:

library(tidyverse)
library(coronavirus)
library(ggrepel)
update_dataset()
#Data
summary_china <- coronavirus %>% 
  filter(type == "confirmed" & country == "China") %>%
  group_by(date) %>% summarise(total_cases = sum(cases)) %>% mutate(country = "China") %>%
  arrange(date) 

summary_not_china <- coronavirus %>% 
  filter(type == "confirmed" & country != "China") %>%
  group_by(date) %>% summarise(total_cases = sum(cases)) %>% mutate(country = "Others") %>%
  arrange(date) 

summary_by_cases <- rbind(summary_china, summary_not_china)

#Data for events
who_events <- tribble(
  ~ date, ~ event,
  "2020-01-30", "Global health\nemergency declared",
  "2020-03-11", "Pandemic\ndeclared",
  "2020-02-13", "China reporting\nchange"
) %>%
  mutate(date = as.Date(date))

现在剧情代码:

#Plot
ggplot(data=summary_by_cases,aes(x=date,y=total_cases,
                                 color=country))+
  geom_line()+
  geom_vline(xintercept=who_events$date,
             color=c('red','green','blue'))+
  annotate(geom = 'label_repel',x=who_events$date,y=2e5,
                 label=who_events$event,
           color=c('red','green','blue'),force=200)

输出: