简体   繁体   中英

Format x-axis date in chr type on facet_wrap using R

*** Updated code so it is reproducible. ***

This question relates to R using RStudio.

I need to format the date on the x-axis as three-letter month and two-digit day, as shown below (Mar 01).

The date is a dataframe itself as date.local, it's of type "chr", and in this format: 2021-04-10T20:00:00+02:00

This is the code I'm using on R:

measurements_page <- fromJSON("https://api.openaq.org/v2/measurements?coordinates=41.385063,2.173404&radius=1200&limit=2000#/")
measurements_df <- as_tibble(measurements_page$results)
# Tried as.Date() but I couldn't get it to work 
#as.Date(measurements_df$date$local, format = "%m/%d/%Y" )
measurements_df %>%
  ggplot() +
  geom_line(mapping = aes(
     x = date$local, 
     y = value,
     group = 1
  )) +
  facet_wrap(~ parameter, scales = "free_y")   

It's supposed to look like this:

在此处输入图像描述

But it looks like this:

在此处输入图像描述

It appears to me like the dates are all superimposed on top of each other in the long format.

How can I fix this?

I tried this:

as.Date(measurements_df$date$local, format = "%m/%d/%Y" )

But I'm getting all NA's

Help is appreciated. Please and Thank you!

Though there already is an accepted answer , here is another one.
I have some doubts on a line graph of these data, see below a scatter plot.

library(dplyr)
library(ggplot2)

measurements_page <- jsonlite::fromJSON("https://api.openaq.org/v2/measurements?coordinates=41.385063,2.173404&radius=1200&limit=2000#/")

measurements_page %>% 
  magrittr::extract2("results") %>%
  mutate(date_local = as.Date(date$local)) %>%
  ggplot(aes(date_local, value)) +
  #geom_line() +
  geom_point() +
  xlab("Date local") +
  facet_wrap(~ parameter, scales = "free_y")

在此处输入图像描述

I just wrapped x variable is aes around as.Date and it worked in my window

measurements_df %>%
  ggplot() +
  geom_line(mapping = aes(
    x = as.Date(date$local), 
    y = value,
    group = 1
  )) +
  facet_wrap(~ parameter, scales = "free_y")

在此处输入图像描述

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