Related
I have a data set of Standardized Precipitation Index values from 1980 to 2005. There is one value for each month, so altogether there are 312 (26 years * 12 months) values. The SPI values range between -3 and +3. Here is an easy reproducible example, since the exact values are not important for my question:
vec1 <- rep(seq(1980, 2005), each= 12)
vec2 <- sample(x = -3:3, size = 312, replace = TRUE)
df <- data.frame(vec1, vec2)
colnames(df) <- c("Year", "SPI")
Now I would like to plot the SPI values with the years being the x-axis.
When I try to plot it using ggplot2:
ggplot() +
geom_line(aes(x=df$Year, y=df$SPI))
Something like this comes out:
So the problem is, there is no continuous line.
I can plot it with a continuous line with Base R for example:
plot(vec2, type="l")
But then the problem is that the x-axis only shows the values 1:312 and I need the years as the x-values.
Anybody with a hint?
EDIT after the answer of marcguery:
It turned out that I cannot use a line plot for my purpose. Instead, I need to do a column plot with many single columns when using ggplot2 since I need to color the areas above/below zero.
marcguery's answer works for a geom_line() plot, but unfortunately not for a geom_col() plot. I have no idea why.
Here is the modified code:
vec1 <- seq(as.Date("1980-01-01"),
by = "month",
to = as.Date("2005-12-01"))
vec2 <- sample(x = -3:3, size = 312, replace = TRUE)
vec3 <- 1:312
df <- data.frame(vec1, vec2, vec3)
colnames(df) <- c("Date", "SPI", "ID")
library(data.table)
df <- as.data.table(df)
This is what unfortunately does not work with the dates as x-axis, there is a strange output:
library(ggplot2)
# with Date as x-axis
ggplot(data= df, aes(x= Date, y= SPI, width= 1)) +
geom_col(data = df[SPI <= 0], fill = "red") +
geom_col(data = df[SPI >= 0], fill = "blue") +
theme_bw()
This is what works with the simple rownumber as x-axis:
# with ID as x-axis
ggplot(data= df, aes(x= ID, y= SPI, width= 1)) +
geom_col(data = df[SPI <= 0], fill = "red") +
geom_col(data = df[SPI >= 0], fill = "blue") +
theme_bw()
I need something like the last example, just with the dates as the x-axis.
Your observations per month of each year have all the same value in your column Year, hence why ggplot cannot assign them different x values. Since you are working with dates, you could use Date format for your time points so that each month is assigned a different value.
#Seed for reproducibility
set.seed(123)
#Data
vec1 <- seq(as.Date("1980-01-01"),
by = "month",
to = as.Date("2005-12-01"))
vec2 <- sample(x = -3:3, size = 312, replace = TRUE)
df <- data.frame(vec1, vec2)
colnames(df) <- c("Date", "SPI")
#Plot
library(ggplot2)
ggplot(df) +
geom_line(aes(x = Date, y = SPI))+
scale_x_date(breaks = "5 years", date_labels = "%Y",
limits = c(as.Date("1979-12-01"),
as.Date("2006-01-01")),
expand = c(0,0))
Edit after you added your question about coloring the area between your values and 0 based on the sign of the values:
You can definitely use a geom_line plot for that purpose. Using a geom_col plot is a possibility but you would loose visual information about change between your x variables which are continuously related as they represent dates.
To plot a nice geom_line, I will base my approach on the answer here https://stackoverflow.com/a/18009173/14027775. You will have to adapt your data by transforming your dates to numerical values, for instance number of days since a given date (typically 1970/01/01).
#Colored plot
#Numerical format for dates (number of days after 1970-01-01)
df$numericDate <- difftime(df$Date,
as.Date("1970-01-01", "%Y-%m-%d"),
units="days")
df$numericDate <- as.numeric(df$Date)
rx <- do.call("rbind",
sapply(1:(nrow(df)-1), function(i){
f <- lm(numericDate~SPI, df[i:(i+1),])
if (f$qr$rank < 2) return(NULL)
r <- predict(f, newdata=data.frame(SPI=0))
if(df[i,]$numericDate < r & r < df[i+1,]$numericDate)
return(data.frame(numericDate=r,SPI=0))
else return(NULL)
}))
#Get back to Date format
rx$Date <- as.Date(rx$numericDate, origin = "1970-01-01")
d2 <- rbind(df,rx)
ggplot(d2,aes(Date,SPI)) +
geom_area(data=subset(d2, SPI<=0), fill="red") +
geom_area(data=subset(d2, SPI>=0), fill="blue") +
geom_line()+
scale_x_date(breaks = "5 years", date_labels = "%Y",
limits = c(as.Date("1979-12-01"),
as.Date("2006-01-01")),
expand = c(0,0))
Now if you want to keep using geom_col, the reason why you don't see all the bars using dates for the x axis is that they are too thin to be filled as they represent one single day over a long period of time. By filling and coloring them, you should be able to see all of them.
ggplot(data= df, aes(x= Date, y= SPI)) +
geom_col(data = df[df$SPI <= 0,],
fill = "red", color="red", width= 1) +
geom_col(data = df[df$SPI >= 0,],
fill = "blue", color="blue", width= 1) +
scale_x_date(breaks = "5 years", date_labels = "%Y",
limits = c(as.Date("1979-12-01"),
as.Date("2006-01-01")),
expand = c(0,0))
I need to visualize and compare the difference in two equally long sales periods. 2018/2019 and 2019/2020. Both periods begin at week 44 and end at week 36 of the following year. If I create a graph, both periods are continuous and line up. If I use only the week number, the values are sorted as continuum and the graph does not make sense. Can you think of a solution?
Thank You
Data:
set.seed(1)
df1 <- data.frame(sells = runif(44),
week = c(44:52,1:35),
YW = yearweek(seq(as.Date("2018-11-01"), as.Date("2019-08-31"), by = "1 week")),
period = "18/19")
df2 <- data.frame(sells = runif(44),
week = c(44:52,1:35),
YW = yearweek(seq(as.Date("2019-11-01"), as.Date("2020-08-31"), by = "1 week")),
period = "19/20")
# Yearweek on x axis, when both period are separated
ggplot(df1, aes(YW, sells)) +
geom_line(aes(color="Period 18/19")) +
geom_line(data=df2, aes(color="Period 19/20")) +
labs(color="Legend text")
# week on x axis when weeks are like continuum and not splited by year
ggplot(df1, aes(week, sells)) +
geom_line(aes(color="Period 18/19")) +
geom_line(data=df2, aes(color="Period 19/20")) +
labs(color="Legend text")
Another alternative is to facet it. This'll require combining the two sets into one, preserving the data source. (This is commonly a better way of dealing with it in general, anyway.)
(I don't have tstibble, so my YW just has seq(...), no yearweek. It should translate.)
ggplot(dplyr::bind_rows(tibble::lst(df1, df2), .id = "id"), aes(YW, sells)) +
geom_line(aes(color = id)) +
facet_wrap(id ~ ., scales = "free_x", ncol = 1)
In place of dplyr::bind_rows, one might also use data.table::rbindlist(..., idcol="id"), or do.call(rbind, ...), though with the latter you will need to assign id externally.
One more note: the default formatting of the x-axis is obscuring the "year" of the data. If this is relevant/important (and not apparent elsewhere), then use ggplot2's normal mechanism for forcing labels, e.g.,
... +
scale_x_date(labels = function(z) format(z, "%Y-%m"))
While unlikely that you can do this without having tibble::lst available, you can replace that with list(df1=df1, df2=df2) or similar.
If you want to keep the x axis as a numeric scale, you can do:
ggplot(df1, aes((week + 9) %% 52, sells)) +
geom_line(aes(color="Period 18/19")) +
geom_line(data=df2, aes(color="Period 19/20")) +
scale_x_continuous(breaks = 1:52,
labels = function(x) ifelse(x == 9, 52, (x - 9) %% 52),
name = "week") +
labs(color="Legend text")
Try this. You can format your week variable as a factor and keep the desired order. Here the code:
library(ggplot2)
library(tsibble)
#Data
df1$week <- factor(df1$week,levels = unique(df1$week),ordered = T)
df2$week <- factor(df2$week,levels = unique(df2$week),ordered = T)
#Plot
ggplot(df1, aes(week, sells)) +
geom_line(aes(color="Period 18/19",group=1)) +
geom_line(data=df2, aes(color="Period 19/20",group=1)) +
labs(color="Legend text")
Output:
Given this example dataset:
date <- seq(as.Date("2019-01-01"), as.Date("2019-12-31"), "days")
Y <- rnorm(length(date),0,1)
data.frame(date, Y) %>% ggplot(aes(y = Y, x = date)) + geom_point()
I get the following default plot:
The vertical lines appear on every 3rd month (1st day), with one in betweeen. I would like these lines to appear on every (1st day of) month.
Is there a way to do this automatically (without specifying the actual dates) - for instance can I tell it that I want 13 lines in total (1 for each month) ? Or any other ways would be interesting.
EDIT: The linked answers for duplicates do not address this situation. They create vertical lines for months AND corresponding labels. I am happy with the labels every 3 months - I just want the vertical lines to be every month
What you're calling tick marks are called breaks in ggplot2 jargon. The ones with labels are major breaks, the ones without are minor breaks. So you can probably get what you want using this code:
date <- seq(as.Date("2019-01-01"), as.Date("2019-12-31"), "days")
Y <- rnorm(length(date),0,1)
data.frame(date, Y) %>% ggplot(aes(y = Y, x = date)) +
geom_point() + scale_x_date(date_minor_breaks = "1 month")
One possible issue is that minor breaks are half the width of major breaks. If you want the one month breaks to be all the same size, you need to change the
theme. For example,
date <- seq(as.Date("2019-01-01"), as.Date("2019-12-31"), "days")
Y <- rnorm(length(date),0,1)
data.frame(date, Y) %>% ggplot(aes(y = Y, x = date)) +
geom_point() + scale_x_date(date_minor_breaks = "1 month") +
theme(panel.grid.minor.x = element_line(size = rel(2)))
I used rel(2) to undo the rel(0.5) for "panel.grid.minor". This leaves the
minor breaks at half width for Y, but sets all breaks to the same size for date:
I'm using ggplot to plot various events as a function of the date (x-axis) and start time (y-axis) on which they began. The data/code are as follows:
date<-c("2013-06-05","2013-06-05","2013-06-04","2013-06-04","2013-06-04","2013-06-04","2013-06-04",
"2013-06-04","2013-06-04","2013-06-03","2013-06-03","2013-06-03","2013-06-03","2013-06-03",
"2013-06-02","2013-06-02","2013-06-02","2013-06-02","2013-06-02","2013-06-02","2013-06-02")
start <-c("07:36:00","01:30:00","22:19:00","22:12:00","20:16:00","19:19:00","09:00:00",
"06:45:00","01:03:00","22:15:00","19:05:00","08:59:00","08:01:00","07:08:00",
"23:24:00","20:39:00","18:53:00","16:57:00","15:07:00","14:33:00","13:24:00")
duration <-c(0.5,6.1,2.18,0.12,1.93,0.95,10.32,
2.25,5.7,2.78,3.17,9.03,0.95,0.88,
7.73,2.75,1.77,1.92,1.83,0.57,1.13)
event <-c("AF201","SS431","BE201","CD331","HG511","CD331","WQ115",
"CD331","SS431","WQ115","HG511","WQ115","CD331","AF201",
"SS431","WQ115","HG511","WQ115","CD331","AS335","CD331")
df<-data.frame(date,start,duration,event)
library(ggplot2)
library(scales)
p <- ggplot(df, aes(as.Date(date),as.POSIXct(start,format='%H:%M:%S'),color=event))
p <- p+geom_point(alpha = I(6/10),size=5)
p + ylab("time (hr)") + xlab("date") + scale_x_date(labels = date_format("%m/%d")) +
scale_y_datetime(labels = date_format("%H"))+
scale_colour_hue(h=c(360, 90))
theme(axis.text.x = element_text(hjust=1, angle=0))
The resulting plot looks like this:
Question: Instead of simply indicating the start time of the event with a single point (shown above), how can I plot a bar that spans the time duration of the event? As shown in the data frame above I have this duration data (in hours). Alternatively, I could supply a 'stop time' (not shown).
I'm imagining the solution would look something like a stacked bar chart. However, a bar chart isn't quite right as it assumes the bar starts at the bottom of the plot and that the vertically stacked events have no gaps between them. My events may be non-contiguous -- 'starting' and 'stopping' at various positions along the y-axis. The solution will also have to take into consideration that 1) some events may ultimately be concurrent (overlap in time) and 2) some events will span multiple days.
I'd be very grateful for any suggestions!
It's a bit unclear exactly what you want - #Michele's answer seemed good, I wasn't clear if you wanted to to use geom_rect because it would make for thicker lines (if so, just change the line width), or if there was another reason. I decided to give it a go using geom_rect to enable dodging. I've plotted it with the starting date on the x axis, and the start and end times on y. I've set up the data slightly differently to enable that. If you're after something different, try to make it explicit, but at least here's another option:
df<-data.frame(date,start,duration,event)
df <- transform(df,
start = as.POSIXct(paste(date, start)),
end = as.POSIXct(paste(date, start)) + duration*3600)
df <- df[c("event", "start", "end")]
df$date <- strptime(df$start, "%Y-%m-%d")
df$start.new <- format(df$start, format = "%H:%M:%S")
df$end.new <- format(df$end, format = "%H:%M:%S")
df$day <- factor(as.POSIXct(df$date))
levels(df$day) <- 1:4
df$day <- as.numeric(as.character(df$day))
df$event.int <- df$event
levels(df$event.int) <- 1:7
df$event.int <- as.numeric(as.character(df$event.int))
p <- ggplot(df, aes(day, start)) + geom_rect(aes(ymin = start, ymax = end,
xmin = (day - 0.45) + event.int/10,
xmax = (day - 0.35) + event.int/10,
fill = event)) +
scale_x_discrete(limits = 1:4,breaks = 1:4, labels = sort(unique(date)),
name = "Start date") + ylab("Duration")
Thanks (+1s) to #Michele and #alexwhan for your input. Using geom_rect I was able to get all of the events which occur on the same date on the same point on the x axis. (I'm anticipating that this data set may ultimately include many months of events.)
df<-data.frame(date,start,duration,event)
library(ggplot2)
p <- ggplot(df, aes(xmin=as.Date(date),xmax=as.Date(date)+1,
ymin=as.POSIXct(start,format='%H:%M:%S'),
ymax=as.POSIXct(start,format='%H:%M:%S')+duration*3600,
fill=event))
p <- p+geom_rect(alpha = I(8/10))
p + ylab("time") + xlab("date") + scale_x_date(labels = date_format("%m/%d")) +
scale_y_datetime(labels = date_format("%H"))+
scale_colour_hue(h=c(360, 90))
theme(axis.text.x = element_text(hjust=1, angle=0))
... resulting in this:
This is pretty close to what I was aiming for.
I think I can deal with the potential overplotting issue by adjusting the alpha.
Ideally I'd like the y axis to include just a single day (00 to 00). To do this I guess I'll probably need to reformat the data such that events with durations that extend beyond midnight are reallocated to the next day. (Not sure how to do this in R.)
try this method. Probably it's different to what you planned but I think it's a quite clear way to show your data:
df<-data.frame(date,start,duration,event)
df <- transform(df,
start = as.POSIXct(paste(date, start)),
end = as.POSIXct(paste(date, start)) + duration*3600)
df <- df[c("event", "start", "end")]
library(reshape2)
df <- melt(df, id.vars="event")
df$value <- as.POSIXct(df$value, origin=as.Date("1970-01-01"))
df <- df[order(df$event, df$value),]
df$eventID <- rep(seq(1, nrow(df)/2, 1), each=2)
library(ggplot2)
ggplot(df) +
geom_line(aes(value, event, group=eventID, color=event))
Combining the benefits of: (i) y-axis containing a single ~24 hour period; (ii) events not overlapping; (iii) events labelled within the graph in addition to the legend; and (iv) concise code.
library(dplyr)
library(lubridate)
# Re-create data frame
df <- data_frame(date, start, duration, event) %>%
mutate(start_dt = as.POSIXct(paste(date, start), tz = 'UTC'),
start_hr = hour(start_dt),
end_dt = start_dt + duration * 3600,
end_hr = hour(end_dt) + (as.Date(end_dt) - as.Date(start_dt)) * 24)
# Plot
df %>% ggplot() +
geom_segment(aes(x = event, y = start_hr, xend = event, yend = end_hr,
color = event, size = 1)) +
facet_wrap(~ date, nrow = 1) +
guides(size = 'none')
Image of plot:
I am trying to develop a weather plot like that appears in weather data - something like.
I want to plot daily value (although average value can appear in circle). I am using ggplot2 as it need multifaceted (for each month and year).
st <- as.Date ("2009-1-1")
en <- as.Date ("2011-12-28")
date1 <- seq(st, en, "1 day")
year <- format(date1, "%Y")
month <- format (date1, "%b")
day <- as.numeric (format(date1, "%d"))
avgtm <- round (rnorm (length(date1), 50,5), 1)
maxtm <- avgtm + abs(rnorm (length (avgtm), 0, 5))
mintm <- avgtm - abs(rnorm (length (avgtm), 0, 5))
myd <- data.frame ( year, month, day, avgtm, maxtm, mintm)
require(ggplot2)
qplot(day, avgtm, data = myd, geom = "line", col = "red") +
facet_grid(year ~ month) + theme_bw()
There is one major problem here, line will connect between months.
Each month is plotted to maximum (although one month can end in 28, leaving blank at the month).
Is there a smart way to achieve what I want to achieve. I tried ggplot2 but there might be other nice options.
Edit:
I am trying to add vertical line at the first day of month to demark the months. Here is I tried to find the first day of month:
td = as.Date (seq(as.Date("2009/1/1"), as.Date("2011/12/28"), "months"))
I tried to use this to plot line:
qplot(date, avgtm, data = myd, geom = "line", col = "red") +
facet_wrap(~year, scales='free_x', ncol=1, nrow=3) +
geom_vline(xintercept=td, linetype="dotted") + theme_bw()
But running an error:
Error : Invalid intercept type: should be a numeric vector, a function, or a name of a function
How can plot the vertical line with the date ?
There is a solution with panel.xblocks from latticeExtra:
st <- as.Date("2009-1-1")
en <- as.Date("2011-12-28")
date1 <- seq(st, en, "1 day")
avgtm <- round (rnorm (length(date1), 50,5), 1)
myd <- data.frame(date1, avgtm)
I define two functions to extract month and year values instead of
including them in the data.frame. This approach is useful with
panel.xblocks in the panel function of xyplot:
month <- function(x)format(x, '%m')
year <- function(x)format(x, '%Y')
I use year(date1) as conditioning variable to produce three
panels. Each of these panels will display the time series for that
year (panel.xyplot) and a sequence of contiguous blocks with
alternating colors to highlight months (panel.xblocks). You
should note that the y argument in panel.xblocks is the
function month previously defined:
xyplot(avgtm ~ date1 | year(date1), data=myd,
type='l', layout=c(1, 3),
scales=list(x=list(relation='free')),
xlab='', ylab='',
panel=function(x, y, ...){
panel.xblocks(x, month,
col = c("lightgray", "white"),
border = "darkgray")
panel.xyplot(x, y, lwd = 1, col='black', ...)
})
How about making a date column, then faceting on year only
myd$date <- as.Date(paste(myd$year, myd$month, myd$day), format='%Y %b %d')
qplot(date, avgtm, data = myd, geom = "line", col = "red") +
facet_wrap(~year, scales='free_x', ncol=1, nrow=3)
You could add scales='free_x' to your plot as well, but will find it makes interpretation difficult.
By faceting on month and year you are telling the viewer and the plotting tool that the variables plotted are not continuous. This is incorrect as you've pointed out in your question. Thus, no faceting... You can add tick marks for each month or each day if you want.
library(scales)
qplot(date, avgtm, data = myd, geom = "line", col = "red") +
facet_wrap(~year, scales='free_x', ncol=1, nrow=3) +
scale_x_date(breaks=date_breaks("month"), labels=date_format("%b"))
Alternatively you could extract day of year and plot everything on one plot, coloring by year:
myd$doy <- format(myd$date, '%j')
p <- ggplot(myd, aes(x=doy, y=avgtm, color=year, group=year))
p + geom_line()
or
p + geom_smooth()