-1

I replicated a code to plot 7-day moving average of currently hospitalized people in every state.

This is my code:

covus %>%
  filter(measure == "hospitalized_currently", state %in% unique(state_pops$state)) %>%
  group_by(state) %>%
  mutate(hospitalized7 = slider::slide_dbl(count, mean, .before = 7, .after = 0, na.rm = TRUE)) %>%
  left_join(state_pops) %>%
  ggplot(mapping = aes(x = date, y = (hospitalized7/pop)*1e5)) + 
  geom_line(size = 0.5) + 
  scale_y_continuous(labels = scales::comma_format(accuracy = 1)) + 
  facet_wrap(~ name, ncol = 4) +
  labs(x = "Date", 
       y = "Hospitalized per 100,000 Population (Seven Day Rolling Average)")

And this is the outcome plot enter image description here

As you can see any curve is readable.

I want something like this: enter image description here

So I thought that 7-day moving average is not in my plot. Is there a way to know that? In addition, Can you give me any suggestion to make my curves readable?

Jose Montoya
  • 147
  • 1
  • 10
  • 1
    Make your plot taller, or plot fewer states as in the example. You need to make more room to actually draw the graphs. A ggplot will try to fill whatever space you give it so give it more space. – MrFlick Jun 26 '20 at 22:06
  • If you provide a sample of your data or a minimum reproducible example ([How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)) you will have a far better chance of getting help with this. – jared_mamrot Jun 26 '20 at 23:50

1 Answers1

0

A very similar approach of what you want can be done using data at this link(I did a similar plot few days ago so you can adapt your dataset): https://www.sendspace.com/file/4ikz5d

The approach uses dplyr and zoo. I hope it can help. Just download data from previous link.

library(ggplot2)
library(dplyr)
library(reshape2)
library(tidyr)
library(stringr)
library(ggcharts)
library(zoo)
library(xlsx)
library(scales)
library(ggrepel)
#Load data
df4 <- read.csv('df4.csv')
df4$Day <- as.Date(df4$Day)
#Create rolling variable
df4 %>% group_by(country) %>% mutate(NewCases=c(0,diff(confirmed)),
                                     RollAvg=rollmean(NewCases,k = 7,fill = NA,align = 'right')) -> df4
#Plot
ggplot(df4, aes(x = Day ,y = RollAvg)) +geom_line(size=1.2,color='blue')+
  scale_x_date(date_breaks = "25 day",date_labels = "%b/%d")+
  theme_bw()+xlab("Date")+ylab('New confirmed cases (Movil mean of 7 days)')+
  facet_wrap(.~country,scales = 'free')+
  theme(axis.text.x = element_text(face="bold"),
        axis.text.y = element_text(face="bold"),
        plot.title = element_text(hjust = 0.5,size=16,face="bold"),
        plot.subtitle = element_text(size=12,face="bold"),
        strip.text.x = element_text(size = 10, face = "bold"),
        legend.position = "none")

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84