Reputation: 367
I am new to R, so I would like to know if its possible to create a chart like the figure below?
I would like to create a custom chart displaying the duration of activities completed by various people at a given time.
Upvotes: 1
Views: 101
Reputation: 1694
I'd like to propose another format for the data, where each activity has a start and an end time.
Load libraries. dplyr
is only used for manipulating the dataset, and not strictly needed.
library(ggplot2)
library(dplyr)
First we read the data set
activities <- read.csv2(
text=
"Person; Activity; Activity start; Activity end
A; Activity 1; 10:30; 11:30
A; Activity 2; 12:00; 13:00
A; Activity 3; 14:00; 16:00
B; Activity 1; 10:30; 11:30
B; Activity 2; 11:30; 13:00
B; Activity 3; 14:00; 14:30"
) %>%
mutate(
Activity.start = as.POSIXct(Activity.start, format="%H:%M"),
Activity.end = as.POSIXct(Activity.end, format="%H:%M"),
Person = as.factor(Person)
)
So now we have the correct classes for the columns and we can plot this with
ggplot(activities) +
geom_rect(
aes(
xmin=Activity.start,
xmax=Activity.end,
fill=Activity,
ymin=as.numeric(Person)-.5,
ymax=as.numeric(Person)+.5)
) +
scale_y_continuous(labels=levels(activities$Person), breaks=1:2) +
geom_text(
aes(x=(Activity.start + (Activity.end - Activity.start)/2), y=as.numeric(Person), label=Activity)
) +
xlab(NULL) +
ylab("Person")
which results in
Upvotes: 1
Reputation: 23211
While this isn't normally the type of graph you'd create in R, surely you could pull it off with sufficient leg work.
I think this will get you jumpstarted:
require(lubridate)
require(ggplot2)
df <- as.data.frame(matrix(nrow=14,ncol=3))
colnames(df) <- c("Person", "Time", "Activity")
df$Person <- c("A","A","A","A","A","A", "A",
"B","B","B","B","B","B", "B")
df$Time <- as.character(hours(c(10,11,12,13,14,15,16)))
df$Activity <- c(NA, "Activity 1", NA, "Activity 2", NA, "Activity 3","Activity 3",
NA, "Activity 1", "Activity 2", NA, NA, "Activity 3", NA)
ggplot(df, aes(Time, Person)) + geom_tile(aes(fill = Activity),
colour = "white") + scale_fill_manual(values = rainbow (3))
You can take it to the next level by exploring the ggplot2
options and doing further customization to get it closer to the picture you drew. For instance you should be able to
geom_label
is one way)just by reading over and tweaking the options. I recently gave an answer on highly customized tick marks which you can find on SO with a quick search.
Upvotes: 1