ggplot2中的日期轴标签落后一天 [英] Date axis labels in ggplot2 is one day behind
问题描述
我正尝试在R中使用 ggplot2
和比例
在x轴上创建日期图。图书馆。问题是,当我使用命令 scale_x_datetime(breaks = date_breaks(width =1 day),labels = date_format(%e。%b))
,休息似乎是好的,但标签落后一天。所以,对于5月1日的数据点,标签是4月30日。
我想这是因为我使用的是离散值的比例尺,它是用于连续数据。无论如何,我如何确保5月1日的标签可以显示5月1日?
library(ggplot2)
library(比例)
$ b $开始< - 2015-05- 01 00:00:00
end< - 2015-05-10 00:00:00
df< - data.frame(
x = seq( as.POSIXct(start)as.POSIXct(end)by =1 day),
y = runif(10,0,20)
)
ggplot( df,aes(x,y))+
geom_point()+
scale_x_datetime(breaks = date_breaks(width =1 day),labels = date_format(%e。%b))
借助@Deena帮助解决方案
<$ p $ (格式(df $ x,%d。%b)),格式(df $ x,%d。%b))
ggplot(df,aes(x,y))+ geom_point()+
scale_x_datetime(breaks = df $ x [breaks.index],
labels = format(df $ X [休息。索引],%e。 %b))
老实说,我没有我们知道为什么我们要在30年前取得成功,但以下是一个解决方案:
#works
ggplot(df ,aes(x,y))+ geom_point()+
scale_x_datetime(breaks = date_breaks(width =day))
#无效
ggplot(df ,aes(x,y))+ geom_point()+
scale_x_datetime(breaks = date_breaks(width =day),labels = date_format(%d。%b))
#在
周围工作ggplot(df,aes(x,y))+ geom_point()+
scale_x_datetime(breaks = df $ x,labels = format(df $ x,%d。%b ))
I am trying to create a plot with dates on the x-axis in R using ggplot2
and the scales
library. The problem is, when I am using the command scale_x_datetime(breaks = date_breaks(width = "1 day"), labels=date_format("%e. %b"))
, the breaks seems to be OK, but the labels are one day behind. So, for the data point for 1st of May, the label is the 30th of April.
I guess it is because I use the scale for discrete value, and it is intended for continuous data. Anyway, how can I make sure that the label for the 1st of May says 1st of May?
library(ggplot2)
library(scales)
start <- "2015-05-01 00:00:00"
end <- "2015-05-10 00:00:00"
df <- data.frame(
x = seq(as.POSIXct(start), as.POSIXct(end), by = "1 day"),
y = runif(10, 0, 20)
)
ggplot(df, aes(x, y)) +
geom_point() +
scale_x_datetime(breaks = date_breaks(width = "1 day"), labels=date_format("%e. %b"))
Solution with help from @Deena
breaks.index <- match(unique(format(df$x, "%d. %b")), format(df$x, "%d. %b"))
ggplot(df, aes(x, y)) + geom_point() +
scale_x_datetime(breaks = df$x[breaks.index],
labels = format(df$x[breaks.index], "%e. %b"))
Honestly, I don't know why we are getting 30April on the axis. But following is a work around:
#works
ggplot(df, aes(x, y)) + geom_point() +
scale_x_datetime(breaks = date_breaks(width = "day"))
#doesn't work
ggplot(df, aes(x, y)) + geom_point() +
scale_x_datetime(breaks = date_breaks(width = "day") , labels = date_format("%d. %b"))
#Work around
ggplot(df, aes(x, y)) + geom_point() +
scale_x_datetime(breaks =df$x , labels = format(df$x, "%d. %b"))
这篇关于ggplot2中的日期轴标签落后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!