Related
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:
I want my X axis text to look like:
J
a
n
not be rotated with the letters turned.
I want to keep it as a date axis. I know I could make it discrete with values of "J\na\na\n" for instance. Perhaps I can map a vector of values like that over the axis.text.x values? It seems like there should be an easier way though.
Below will demonstrate the issue. I've rotated it 90 degrees but as shown above this is not what I want.
library(tidyverse)
library(scales)
y<- c(52014,51598,61920,58135,71242,76254,63882,64768,53526,55290,45490,35602)
months<-seq(as.Date("2018-01-01"),as.Date("2018-12-01"),"month")
dat<-as.tibble(cbind(y,months)) %>%
mutate(month=as.Date(months,origin="1970-01-01"))
ggplot(dat) +
geom_line(aes(x=month,y=y)) +
scale_x_date(breaks=date_breaks("month"),labels=date_format("%b")) +
theme(axis.text.x=element_text(angle=90))
Example data :
date <- seq(from = as.Date("2000-01-01"), to = as.Date("2000-12-01"), by = "month")
df <- data.frame(Month = date, Value = rnorm(12))
First, produce a custom set of dates you want. Here I use strsplit() and lapply to achieve your request.(month.name and month.abb are native character vectors in R )
mon.split <- strsplit(month.name, "")
mon <- unlist(lapply(mon.split, paste0, "\n", collapse = ""))
mon
[1] "J\na\nn\nu\na\nr\ny\n" "F\ne\nb\nr\nu\na\nr\ny\n"
[3] "M\na\nr\nc\nh\n" "A\np\nr\ni\nl\n"
[5] "M\na\ny\n" "J\nu\nn\ne\n"
[7] "J\nu\nl\ny\n" "A\nu\ng\nu\ns\nt\n"
[9] "S\ne\np\nt\ne\nm\nb\ne\nr\n" "O\nc\nt\no\nb\ne\nr\n"
[11] "N\no\nv\ne\nm\nb\ne\nr\n" "D\ne\nc\ne\nm\nb\ne\nr\n"
I supposed your date variable is 'Date' class so I use scale_x_date. If it's numeric or character, use scale_x_continuous and scale_x_discrete.
ggplot(df, aes(x = Month, y = Value)) +
geom_line() +
scale_x_date(breaks = date, labels = mon)
I’m putting together some functions to help summarize temporal data in fiscal quarters. Function I have will take a date—e.g. 2017-01-01—and spit out factored character value that corresponds—e.g. ”1Q2017”. I’m using my data to create graphs in ggplot. But since I factor the quarters, I can’t use attributes like geom_line() to connect my data points, like you would for dates.
Can I create a data type for quarters that displays as quarters but behaves like dates? How would I do this?
The "yearqtr" class in zoo represents year/quarters but acts sort of like dates in so far as internally such objects are represented numerically as year + frac where frac is 0, 1/4, 2/4, 3/4 and one can perform arithmetic on them and they format as meaningful year/quarter strings and work with lines in ggplot2 (and classic graphics and lattice graphics). See ?yearqtr and ?scale_x_yearqtr.
library(ggplot2)
library(zoo)
# test data
dates <- c("2017-01-01", "2017-04-01")
values <- 1:2
z <- zoo(values, as.yearqtr(dates)) # test zoo object
# 1. classic graphics
plot(z, axat = "n")
axis(1, at = time(z), labels = format(time(z), "%YQ%q"))
# 2. ggplot2 graphics
autoplot(z) + scale_x_yearqtr()
# 3. ggplot2 graphics using data frame with yearqtr
DF <- fortify.zoo(z) # test data frame
sapply(DF, class)
## Index z
## "yearqtr" "integer"
ggplot(DF, aes(Index, z)) + geom_line() + scale_x_yearqtr()
Taking the comment from #Jaap and incorporating with example graph:
library(ggplot2)
library(zoo)
df <- data.frame(date1 = c("2017-01-01", "2016-10-01", "2016-07-01"),
v1 = c(2, 4, 3))
df$date1 <- as.Date(df$date1)
ggplot(df, aes(x = date1, y = v1)) +
geom_line() +
scale_x_date(name = "quarters",
date_labels = as.yearqtr)
You just need to specify group=1 in aes.
library(tidyverse) # install.packages('tidyverse') if needed
dat = data_frame(date = seq.Date(as.Date('2017-01-01'),
as.Date('2017-12-31'),
length.out=365),
x = rnorm(365))
dat = mutate(dat, qtr = paste0(lubridate::quarter(date), 'Q', lubridate::year(date)))
dat$qtr = as.factor(dat$qtr) # for similarity to your situation
dat %>%
group_by(qtr) %>%
summarise(n = sum(x)) %>%
ggplot(aes(x=qtr, y=n, group=1)) +
geom_line()
I want the x-axis in the following graph to start at 06:00 and end at 22:00, with breaks at every 4 hours. I can't figure out the following, however.
a) How to make the x-axis start at 06:00 without any empty space before 06:00.
b) How to make the x-axis end at 22:00 without any empty space after 22:00. Right now it doesn't even show 22:00
c) How to have breaks at every 4 hours.
d) How to assign a label to the y-axis (currently it's simply X4, the column name).
I've tried several things, but without success. Some example data:
range <- seq(as.POSIXct("2015/4/18 06:00"),as.POSIXct("2015/4/18 22:00"),"mins")
df <- data.frame(matrix(nrow=length(range),ncol=4))
df[,1] <- c(1:length(range))
df[,2] <- 2*c(1:length(range))
df[,3] <- 3*c(1:length(range))
df[,4] <- range
Reshape:
library(reshape2)
df2 <- melt(df,id="X4")
Graph:
library(ggplot2)
ggplot(data=df2,aes(x=X4,y=value,color=variable)) + geom_line()+
scale_y_continuous(expand=c(0,0)) +
coord_cartesian(xlim=c(as.POSIXct("2015/4/18 06:00:00"),as.POSIXct("2015/4/18 22:00:00")))
Which makes the graph look like this:
Any ideas?
Here is some code that should help you. This can easily be done using scale_x_datetime.
## desired start and end points
st <- as.POSIXct("2015/4/18 06:00:00")
nd <- as.POSIXct("2015/4/18 22:00:00")
## display data for given time range
ggplot(data = df2, aes(x = X4, y = value, color = variable)) +
geom_line() +
scale_y_continuous("Some name", expand = c(0, 0)) +
scale_x_datetime("Some name", expand = c(0, 0), limits = c(st, nd),
breaks = seq(st, nd, "4 hours"),
labels = strftime(seq(st, nd, "4 hours"), "%H:%S"))
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: