Programatically display date range with R scale limits - r

Currently using ggplot2 and scales doing this but would be ideal to show a date range +/- 1 Year (for example). I shouldn't really be hardcoding these dates as it's not very efficient.
library(scales) #date time scales
library(ggplot2) # Visualization
ggplot(dataset,aes(x=datetime_start, y=dataset$Product, color=Stage, order = - as.numeric(Stage))) +
geom_segment(aes(x=From,xend=To,yend=dataset$Product), size=10) +
scale_x_datetime(
breaks = date_breaks("1 month"),
labels=date_format("%b%y"),
limits = c(
as.POSIXct("2016-03-01"),
as.POSIXct("2018-02-01")
)
) +

Expand the scale:
library(ggplot2)
df <- data.frame(x = seq(Sys.Date()-lubridate::years(2), Sys.Date(), by="3 month"))
df$y <- 1:nrow(df)
p <- ggplot(df, aes(x, y)) + geom_line()
p + scale_x_date(expand = c(0, 365))

Related

How to plot time in the x-axis? [duplicate]

I have tried to read through stackoverflow, blogs, books etc but have been unable to find the answer on plotting time in the x-axis in the following format(HH:MM:SS.000) in R and another quantity on the y-axis. I have the following dataset:
Time EcNo
12:54:09.000 -14.47
12:54:10.000 -17.96
12:54:11.000 -15.97
12:54:12.000 -14.61
12:54:13.000 -12.68
12:54:14.000 -10.73
12:54:15.000 -10.54
12:54:16.000 -11.62
12:54:17.000 -12.49
12:54:18.000 -11.12
How would I plot EcNo on Yaxis vs Time(x axis) in the format HH:MM:SS.000 as shown above.
I honestly would appreciate some help.
many thanks
You may also try ggplot:
library(ggplot2)
df$time <- as.POSIXct(strptime(df$Time, format="%H:%M:%S"))
# Automatic scale selection
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point()
scale_x_datetime is a ggplot function, but for the nice arguments date_breaks, and date_format you need package scales:
library(scales)
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point() +
scale_x_datetime(breaks = date_breaks("1 sec"), labels = date_format("%S"))
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point() +
scale_x_datetime(breaks = date_breaks("1 sec"), labels = date_format("%OS3"))
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point() +
scale_x_datetime(breaks = date_breaks("4 sec"), labels = date_format("%M:%S"))
plot(strptime(dta$Time, format="%H:%M:%S"), dta$EcNo, xaxt="n")
axis(1, at=as.numeric(strptime(dta$Time, format="%H:%M:%S")),
labels=strftime( strptime(dta$Time, format="%H:%M:%S"),format="%H:%M:%S"))
df <- data.frame(
Time=c('12:54:09.000','12:54:10.000','12:54:11.000','12:54:12.000','12:54:13.000','12:54:14.000','12:54:15.000','12:54:16.000','12:54:17.000','12:54:18.000'),
EcNo=c(-14.47,-17.96,-15.97,-14.61,-12.68,-10.73,-10.54,-11.62,-12.49,-11.12)
)
op <- options(digits.secs=3)
plot(as.POSIXct(df$Time,format="%H:%M:%OS"),df$EcNo,xaxt="n")
axis.POSIXct(1, as.POSIXct(df$Time,format="%H:%M:%OS"), format="%H:%M:%OS")

R ggplot2 - Plot year variable one over the other in same plot

How do I plot each year as a separate line in ggplot2 I tried the below code but it seems to plot continuous as a single plot.
library(ggplot2)
# Dummy data
data <- data.frame(
Date = c(as.Date("2017-01-14") - 0:13,as.Date("2016-01-14") - 0:13),
value = runif(28)
)
#data$Date <- strptime(data$Date, "%Y-%m-%d" )
data$Year <- as.character(year(data$Date))
data$Year <- factor(data$Year)
ggplot(data) + geom_line(aes(x = Date, y = value, group=Year, color=Year)) +
scale_x_date(date_breaks = "1 day", date_labels = "%d-%m-%y") +
theme(axis.text.x = element_text(angle = 90))
But I want each year to be a separate graph in the same plot.
something like below
Try this approach formating day and month in your date. You got a mess in your plot because of the different year in your date variable. Setting format can help you. Here the code:
library(ggplot2)
library(lubridate)
# Dummy data
data <- data.frame(
Date = c(as.Date("2017-01-14") - 0:13,as.Date("2016-01-14") - 0:13),
value = runif(28)
)
data$Year <- as.character(year(data$Date))
data$Year <- factor(data$Year)
#Format month
data$MonthDay <- format(data$Date,'%b-%d')
#Plot
ggplot(data) + geom_line(aes(x = MonthDay, y = value, group=Year, color=Year)) +
theme_bw()+
theme(axis.text.x = element_text(angle = 90))
Output:

Plotting non-overlapping levels of a factor on a circular plot using ggplot2, R

I am trying to create a circular plot to the display frequency/counts of months in my dataset but I would also like to group the months by season. Here is a similar plot for time of day, and now I would like to use the same approach to plot months/seasons. However, for some reason I can't seem to specify the right option to break my scale into non-overlapping month categories. Any suggestions are much appreciated.
library(lubridate)
library(ggplot2) # use at least 0.9.3 for theme_minimal()
library(circular)
### PLOT FOR HOURS ###
## generate random data in POSIX date-time format
set.seed(44)
N=500
events <- as.POSIXct("2011-01-01", tz="GMT") +
days(floor(365*runif(N))) +
hours(floor(24*rnorm(N))) + # using rnorm here
minutes(floor(60*runif(N))) +
seconds(floor(60*runif(N)))
# extract hour with lubridate function
hour_of_event <- hour(events)
# make a dataframe
eventdata <- data.frame(datetime = events, eventhour = hour_of_event)
# determine if event is in business hours
eventdata$Workday <- eventdata$eventhour %in% seq(6, 18)
ra<-length(eventdata[,2])
for (i in 1:ra){
if(eventdata[,3][i]=="TRUE"){eventdata$diel[i]<-"day"}else{eventdata$diel[i]<-"night"}
}
# Plot
ggplot(eventdata, aes(x = eventhour, fill = diel)) +
geom_histogram(breaks = seq(0,24), width = 2, colour = "grey") +
coord_polar(start = 0) + theme_minimal() +
scale_fill_brewer() + ylab("Count") + ggtitle("Events by Time of day") +
scale_x_continuous("", limits = c(0, 24), breaks = seq(0, 24), labels = seq(0,24))
This is my attempt to do a plot by month/season,
### PLOT FOR MONTHS ###
head(events)
# extract hour with lubridate function
month_of_event <- month(events)
# make a dataframe
eventdata <- data.frame(datetime = events, months = month_of_event)
# classify months into seasons
summer<-c(1,2,12)
fall<-c(3,4,5)
winter<-c(6,7,8)
spring<-c(9,10,11)
season.names <- rep("",12)
season.names[summer] <- "Summer"
season.names[fall] <- "Fall"
season.names[winter] <- "Winter"
season.names[spring] <- "Spring"
season.names
eventdata$season<-season.names[eventdata$months]
str(eventdata)
# Plot
ggplot(eventdata, aes(x = months, fill = season)) +
geom_histogram(breaks = seq(0,12, by=1), width = 4) +
coord_polar(start = 0) + theme_minimal() +
scale_fill_brewer() + ylab("Count") +
scale_x_continuous("", limits = c(0, 12), breaks = seq(0, 12), labels = seq(0,12))
Following simple version works:
ggplot(eventdata, aes(x = factor(months), fill = season)) +
geom_histogram()+
coord_polar()

How do I plot time (HH:MM:SS) in X axis in R

I have tried to read through stackoverflow, blogs, books etc but have been unable to find the answer on plotting time in the x-axis in the following format(HH:MM:SS.000) in R and another quantity on the y-axis. I have the following dataset:
Time EcNo
12:54:09.000 -14.47
12:54:10.000 -17.96
12:54:11.000 -15.97
12:54:12.000 -14.61
12:54:13.000 -12.68
12:54:14.000 -10.73
12:54:15.000 -10.54
12:54:16.000 -11.62
12:54:17.000 -12.49
12:54:18.000 -11.12
How would I plot EcNo on Yaxis vs Time(x axis) in the format HH:MM:SS.000 as shown above.
I honestly would appreciate some help.
many thanks
You may also try ggplot:
library(ggplot2)
df$time <- as.POSIXct(strptime(df$Time, format="%H:%M:%S"))
# Automatic scale selection
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point()
scale_x_datetime is a ggplot function, but for the nice arguments date_breaks, and date_format you need package scales:
library(scales)
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point() +
scale_x_datetime(breaks = date_breaks("1 sec"), labels = date_format("%S"))
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point() +
scale_x_datetime(breaks = date_breaks("1 sec"), labels = date_format("%OS3"))
ggplot(data = df, aes(x = time, y = EcNo)) + geom_point() +
scale_x_datetime(breaks = date_breaks("4 sec"), labels = date_format("%M:%S"))
plot(strptime(dta$Time, format="%H:%M:%S"), dta$EcNo, xaxt="n")
axis(1, at=as.numeric(strptime(dta$Time, format="%H:%M:%S")),
labels=strftime( strptime(dta$Time, format="%H:%M:%S"),format="%H:%M:%S"))
df <- data.frame(
Time=c('12:54:09.000','12:54:10.000','12:54:11.000','12:54:12.000','12:54:13.000','12:54:14.000','12:54:15.000','12:54:16.000','12:54:17.000','12:54:18.000'),
EcNo=c(-14.47,-17.96,-15.97,-14.61,-12.68,-10.73,-10.54,-11.62,-12.49,-11.12)
)
op <- options(digits.secs=3)
plot(as.POSIXct(df$Time,format="%H:%M:%OS"),df$EcNo,xaxt="n")
axis.POSIXct(1, as.POSIXct(df$Time,format="%H:%M:%OS"), format="%H:%M:%OS")

R ggplot and facet grid: how to control x-axis breaks

I am trying to plot the change in a time series for each calendar year using ggplot and I am having problems with the fine control of the x-axis. If I do not use scale="free_x" then I end up with an x-axis that shows several years as well as the year in question, like this:
If I do use scale="free_x" then as one would expect I end up with tick labels for each plot, and that in some cases vary by plot, which I do not want:
I have made various attempts to define the x-axis using scale_x_date etc but without any success. My question is therefore:
Q. How can I control the x-axis breaks and labels on a ggplot facet grid so that the (time series) x-axis is identical for each facet, shows only at the bottom of the panel and is in the form of months formatted 1, 2, 3 etc or as 'Jan','Feb','Mar'?
Code follows:
require(lubridate)
require(ggplot2)
require(plyr)
# generate data
df <- data.frame(date=seq(as.Date("2009/1/1"), by="day", length.out=1115),price=runif(1115, min=100, max=200))
# remove weekend days
df <- df[!(weekdays(as.Date(df$date)) %in% c('Saturday','Sunday')),]
# add some columns for later
df$year <- as.numeric(format(as.Date(df$date), format="%Y"))
df$month <- as.numeric(format(as.Date(df$date), format="%m"))
df$day <- as.numeric(format(as.Date(df$date), format="%d"))
# calculate change in price since the start of the calendar year
df <- ddply(df, .(year), transform, pctchg = ((price/price[1])-1))
p <- ggplot(df, aes(date, pctchg)) +
geom_line( aes(group = 1, colour = pctchg),size=0.75) +
facet_wrap( ~ year, ncol = 2,scale="free_x") +
scale_y_continuous(formatter = "percent") +
opts(legend.position = "none")
print(p)
here is an example:
df <- transform(df, doy = as.Date(paste(2000, month, day, sep="/")))
p <- ggplot(df, aes(doy, pctchg)) +
geom_line( aes(group = 1, colour = pctchg),size=0.75) +
facet_wrap( ~ year, ncol = 2) +
scale_x_date(format = "%b") +
scale_y_continuous(formatter = "percent") +
opts(legend.position = "none")
p
Do you want this one?
The trick is to generate day of year of a same dummy year.
UPDATED
here is an example for the dev version (i.e., ggplot2 0.9)
p <- ggplot(df, aes(doy, pctchg)) +
geom_line( aes(group = 1, colour = pctchg), size=0.75) +
facet_wrap( ~ year, ncol = 2) +
scale_x_date(label = date_format("%b"), breaks = seq(min(df$doy), max(df$doy), "month")) +
scale_y_continuous(label = percent_format()) +
opts(legend.position = "none")
p

Resources