简体   繁体   English

使用 R 在 facet_wrap 上以 chr 类型格式化 x 轴日期

[英]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.这个问题与使用 RStudio 的 R 有关。

I need to format the date on the x-axis as three-letter month and two-digit day, as shown below (Mar 01).我需要将 x 轴上的日期格式化为三个字母的月份和两位数的日期,如下所示(3 月 1 日)。

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日期是 dataframe 本身作为 date.local,它的类型为“chr”,格式为:2021-04-10T20:00:00+02:00

This is the code I'm using on R:这是我在 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但我得到了所有的 NA

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.我对这些数据的折线图有些疑问,请参见下面的散点图 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我刚刚将 x 变量包裹在aes周围,它在我的as.Date中工作

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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