问题描述
*** 更新代码,使其可重现。 ***
这个问题与使用 RStudio 的 R 有关。
我需要将 x 轴上的日期格式化为三个字母的月份和两位数的日期,如下所示(Mar 01)。
日期是一个数据框本身,如date.local,它的类型为“chr”,格式如下:2021-04-10T20:00:00+02:00
这是我在 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")
它应该是这样的:
但它看起来像这样:
在我看来,日期都以长格式叠加在一起。
我该如何解决这个问题?
我试过了:
as.Date(measurements_df$date$local,format = "%m/%d/%Y" )
但我得到了所有的 NA
感谢帮助。请和谢谢!
解决方法
虽然已经有一个 accepted answer,但这里还有一个。
我对这些数据的折线图有些怀疑,请看下面的散点图。
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")
,
我刚刚在 aes
周围包裹了 x 变量是 as.Date
并且它在我的窗口中工作
measurements_df %>%
ggplot() +
geom_line(mapping = aes(
x = as.Date(date$local),y = value,group = 1
)) +
facet_wrap(~ parameter,scales = "free_y")