I would like to get nice graphs with date, weekdays, and time as x-axis labels.
test <- data.frame(date=seq(as.POSIXct("2012-02-09 00:00:00",tz="CET"),as.POSIXct("2012-02-11 00:00:00",tz="CET"),"hours" ),
value= runif(49) )
ggplot() + geom_line(data=test, aes(x=as.POSIXct(date), y=value)) +
theme(text=element_text(size=16),
legend.text=element_text(size=16),
axis.text=element_text(size=16, colour="black"),
panel.background = element_rect(fill = 'white', colour = 'black'),
axis.title.y = element_text(size=16, vjust = 0.3),
axis.title.x = element_text(size=16, vjust = 0),
legend.key=element_rect(fill="white")) +
scale_x_datetime( breaks = date_breaks("1 days"), labels = date_format("%a-%d\n%H:%M", tz="CET"),
,limits = c(as.POSIXct("2012-02-09 00:00:00 CET"),as.POSIXct("2012-02-11 00:00:00 CET")))
Including scale_x_datetime as included in the MWE it looks like this:
There are several problems/questions:
1) How can I remove the blank spaces on the left- and right-hand side? Defining limits() was not successful.
2) How can I set the time (hour) that is shown, or in other words, at which timestamp the labels are placed?
3) When I change the timestamp like this
test <- data.frame(date=seq(as.POSIXct("2012-02-09 00:59:00",tz="CET"),as.POSIXct("2012-02-11 00:59:00",tz="CET"),"hours" ),
value= runif(49) )
the resulting plot(s) still show the timestamp with 00 minutes. Is there a way to change this?
You have complete control of the breaks if you make a vector of date-times and give that to the breaks
argument. Below I've done this with seq
.
Setting expand = c(0, 0)
stops ggplot giving extra space.
ggplot(data = test, aes(x = as.POSIXct(date), y = value)) +
geom_line() +
scale_x_datetime(
breaks = seq(as.POSIXct("2012-02-09 00:59:00 CET"),
as.POSIXct("2012-02-11 00:59:00 CET"), "8 hours"),
labels = date_format("%a-%d\n%H:%M", tz = "CET"),
expand = c(0, 0),
limits = c(
as.POSIXct("2012-02-09 00:00:00 CET"),
as.POSIXct("2012-02-11 00:00:00 CET")
)
)
With the limit, I am getting a warning message: "Removed 9 rows containing missing values (geom_path)"
I used expand
as suggested by Richard and below are the code and figure:
test <- data.frame(date=seq(as.POSIXct("2012-02-09 00:00:00",tz="CET"),as.POSIXct("2012-02-11 00:00:00",tz="CET"),"hours" ),
value= runif(49) )
ggplot() + geom_line(data=test, aes(x=as.POSIXct(date), y=value)) +
theme(text=element_text(size=16),
legend.text=element_text(size=16),
axis.text=element_text(size=16, colour="black"),
panel.background = element_rect(fill = 'white', colour = 'black'),
axis.title.y = element_text(size=16, vjust = 0.3),
axis.title.x = element_text(size=16, vjust = 0),
legend.key=element_rect(fill="white")) +
scale_x_datetime( breaks = date_breaks("8 hours"),
labels = date_format("%a-%d\n%H:%M", tz="CET"),
expand = c(0,0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With