使用累计量在ggplot中进行绘图

问题描述 投票:0回答:1

我正在尝试使用ggplot2绘制日期列与数字列。

我有一个数据框,我正在尝试与作为中国或不属于中国的国家/地区一起使用,并成功创建了以下与以下链接的数据框:

is_china <- confirmed_cases_worldwide %>%
  filter(country == "China", type=='confirmed') %>%
  group_by(country) %>%
  mutate(cumu_cases = cumsum(cases)) 

is_not_china <- confirmed_cases_worldwide %>%
  filter(country != "China", type=='confirmed') %>%
  mutate(cumu_cases = cumsum(cases))

is_not_china$country <- "Not China"

china_vs_world <- rbind(is_china,is_not_china)

[现在基本上,我正在尝试在“中国”和“非中国”之间绘制带有cumu_casesdate的折线图我正在尝试执行以下代码:

plt_china_vs_world <- ggplot(china_vs_world) +
  geom_line(aes(x=date,y=cumu_cases,group=country,color=country)) +
  ylab("Cumulative confirmed cases") 

现在,我不断得到如下图:enter image description here

不知道为什么会这样,一直在尝试转换数据类型和其他方法。感谢您的帮助,我在下面都链接了两个csv

https://github.com/king-sules/Covid

r ggplot2 dplyr cumsum
1个回答
0
投票

重复其他“国家”的“日期”,因为现在“国家”已更改为“非中国”。可以在OP的“ is_not_china”步骤中进行更改,也可以在“ china_vs_world”中进行更改]

library(ggplot2)
library(dplyr)
china_vs_world %>%
   group_by(country, date) %>%
   summarise(cumu_cases = sum(cases)) %>% 
   ungroup %>% 
   mutate(cumu_cases = cumsum(cumu_cases)) %>%
   ggplot() +  
    geom_line(aes(x=date,y=cumu_cases,group=country,color=country)) + 
       ylab("Cumulative confirmed cases") 

-输出

enter image description here

注意:该比例尺显示中国的数字很小。

正如@Edward提到的,对数刻度将使它更易于理解

china_vs_world %>%
   group_by(country, date) %>%
   summarise(cumu_cases = sum(cases)) %>% 
   ungroup %>% 
   mutate(cumu_cases = cumsum(cumu_cases)) %>%
   ggplot() +  
    geom_line(aes(x=date,y=cumu_cases,group=country,color=country)) + 
       ylab("Cumulative confirmed cases") +     
    scale_y_continuous(trans='log')

enter image description here

或带有facet_wrap

china_vs_world %>% 
   group_by(country, date) %>%
   summarise(cumu_cases = sum(cases)) %>% 
   ungroup %>%
   mutate(cumu_cases = cumsum(cumu_cases)) %>%      
  ggplot() +  
    geom_line(aes(x=date,y=cumu_cases,group=country,color=country)) + 
      ylab("Cumulative confirmed cases") +
    facet_wrap(~ country, scales = 'free_y')

enter image description here

数据

china_vs_world <- read.csv("https://raw.githubusercontent.com/king-sules/Covid/master/china_vs_world.csv", stringsAsFactors = FALSE)
china_vs_world$date <- as.Date(china_vs_world$date)
© www.soinside.com 2019 - 2024. All rights reserved.