-1

All right?

I have a little problem with ggplot. I plot a related covid chart from a province of my country, but they are a few month and the chart appear with a lot of date numbers. I want to reduce it, but I don´t know how do it.

This is the .csv Baleares .csv

And this is the code:

    library(tidyverse)

baleares<- read.csv("C:/Users/......baleares.csv",fileEncoding = "UTF-8", header = TRUE, sep = ";")



  ggplot(baleares, aes(x=date, group = 1)) + 
  geom_line(aes(y = activos, colour = "Casos Activos"),  size=1.5) + 
  geom_line(aes(y = hospitalized , colour="Hospitalizados") , size=1.5) + 
  
  theme(legend.position="top")+
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) 
Raul
  • 139
  • 9
  • You aren't dealing with dates, you're plotting strings that look like dates. You need to convert with `as.Date`, and then you will (a) get better axis labels, (b) have a continuous axis (vice the categorical you have now), and (c) can adjust/control it now with `ggplot2::scale_x_date`. – r2evans Aug 22 '20 at 16:41

1 Answers1

3

I would suggest two approaches recalling what @r2evans said in comments. In first if you change your x variable from factor to date, you will get an output like this:

library(tidyverse)
#Data
baleares<- read.csv("baleares.csv",fileEncoding = "UTF-8", header = TRUE, sep = ";")
#Format date
baleares$date <- as.Date(baleares$date)
#Plot 01
ggplot(baleares, aes(x=date, group = 1)) + 
  geom_line(aes(y = activos, colour = "Casos Activos"),  size=1.5) + 
  geom_line(aes(y = hospitalized , colour="Hospitalizados") , size=1.5) + 
  theme(legend.position="top")+
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) 

enter image description here

Or you could add scale_x_date() and play around breaks argument to set the time width. Also format labels with date_labels:

#Plot 02
ggplot(baleares, aes(x=date, group = 1)) + 
geom_line(aes(y = activos, colour = "Casos Activos"),  size=1.5) + 
  geom_line(aes(y = hospitalized , colour="Hospitalizados") , size=1.5) + 
  scale_x_date(date_labels="%d-%b-%Y",breaks = '5 days',expand = c(0.01,0))+
  theme(legend.position="top")+
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) 

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84