1

I am new to R and I am currently learning how to plot with ggplot2. I downloaded some COVID-19 data and I am trying to create a plot where the x axis is the date and the y is the cases.

Data frame

My code is given below:

data<- structure(list(date = structure(c(18344, 18343, 18341, 18340, 
18339, 18338, 18337, 18336, 18333, 18331, 18330, 18329, 18328, 
18325), class = "Date"), cases = c(69L, 71L, 36L, 91L, 92L, 57L, 48L, 23L, 
252L, 75L, 7L, 8L, 3L, 3L)), class = "data.frame", row.names = 
c(1548L,1549L, 1551L, 1552L, 1553L, 1554L, 1555L, 1556L, 1559L, 1561L, 
1562L, 1563L, 1564L, 1567L))

library(ggplot2)

a<- ggplot(data=data, aes(x=date, y=cases)) +
geom_point() +
geom_line()+
scale_x_date(date_breaks = "1 day", date_labels =  "%d %b %Y") +
theme(axis.text.x=element_text(angle=60, hjust=1)) 

a

Unfortunately, I am not able to make the line smooth (it appears as jagged from day to day), although I have tried to use the information I have seen on other posts.

I would appreciate any help :) Thanks

user13069688
  • 341
  • 2
  • 11
  • 2
    If you provide your dataframe in the right format, you'd get help much easily here, cause that helps people reproduce the particular scenario. Please take a look at [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), to modify your question, with a smaller sample taken from your data (check `?dput()`). – massisenergy Mar 24 '20 at 13:35
  • After your edit (and correcting `data = denmark` to `data = df`), the line looks perfectly straight. You need to post data that has the problems you are describing, and you should try to make sure the code you post actually works: the `reprex` package helps with this. – user2554330 Mar 24 '20 at 16:07
  • Hi and thank you very much. I am so sorry but I am completely new to this :) I have just corrected it. Hope it works :) thanks again! – user13069688 Mar 24 '20 at 19:07

2 Answers2

1

Have you tried geom_smooth?

a<- ggplot(data=denmark, aes(x=date, y=cases)) +
geom_point() +
geom_smooth(method = "loess") +
scale_x_date(date_breaks = "1 day", date_labels =  "%d %b %Y") +
theme(axis.text.x=element_text(angle=60, hjust=1)) 
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
  • Hi, thank you! Yes I have tried geom_smooth() without giving any additional parameters but it adds a complete random line to my plot! – user13069688 Mar 24 '20 at 13:33
-1

Have you cofigure the date as.Date and order the data by date before try to plot?

like this:

denmark <- denmark[order(denmark$date),]

Hope it helps you!