简体   繁体   中英

line plot on bar chart with ggplot2

我想在每个条上绘制这条线,但奇怪的原因是这条线在条内 这是数据集的概述数字是移动平均线

I would like to present the data visualisation which includes line chart and bar chart. Could you guys tell me what kind of mistakes I have made? I guess if it because the moving weighted average caused this issue?

rollmean_covid  <- covid_ts1  %>% filter(Nation == "England") %>% select(date, daily_pos_num) %>% 
    mutate(pos_num01 = rollmean(daily_pos_num, k = 3, fill = NA),
           pos_num02 = rollmean(daily_pos_num, k = 5, fill = NA),
           pos_num03 = rollmean(daily_pos_num, k = 7, fill = NA),
           pos_num04 = rollmean(daily_pos_num, k = 10, fill = NA),
           pos_num05 = rollmean(daily_pos_num, k = 14, fill = NA))

rollmean_covid_metric <- rollmean_covid %>% gather(metric, number, pos_num01:pos_num05)
rollmean_covid_metric %>% filter(metric == "pos_num01") %>% 
  ggplot() + 
  geom_line(aes(date, number), col = "Blue") +
  geom_col(aes(date, number), fill = "orange", alpha = 0.7)

edited1: the dataset overview is provided bellow.

# A tibble: 10 x 7
   date       daily_pos_num pos_num01 pos_num02 pos_num03 pos_num04 pos_num05
   <date>             <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>
 1 2020-01-30             2    NA          NA      NA          NA      NA    
 2 2020-01-30             0     0.667      NA      NA          NA      NA    
 3 2020-01-31             0     0           0.4    NA          NA      NA    
 4 2020-01-31             0     0           0       0.286      NA      NA    
 5 2020-02-01             0     0           0       0           0.3    NA    
 6 2020-02-01             0     0           0       0.143       0.1    NA    
 7 2020-02-02             0     0           0.2     0.143       0.1     0.286
 8 2020-02-02             0     0.333       0.2     0.143       0.2     0.143
 9 2020-02-03             1     0.333       0.2     0.143       0.2     0.143
10 2020-02-03             0     0.333       0.2     0.286       0.2     0.143

You have multiple observations for one date, and by default the position = "stack" for geom_col so that's why the bars are taller. You probably want position = "identity" , this should work:

rollmean_covid_metric %>% 
    filter(metric == "pos_num01") %>% 
    ggplot(aes(date, number)) + 
    geom_line(color = "blue") +
    geom_col(position = "identity", fill = "orange", alpha = 0.7)

Edit to add: as @chemdork123 points out in the comments, if one date has multiple values this probably won't give desired results. In general, the best solution for these types of problems is to munge your data into the correct shape before piping it into a ggplot call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM