Reputation: 470
I would like to make a graph that represents the frequency of an event per hour of each day of the week. How do I change the color of the day of the week? I would like to switch from black to red to the proximity of the weekend
weekday_hour_pickup <- my_data %>%
mutate(hour_pick = hour(new_pickup))%>%
group_by(hour_pick, weekday) %>%
count() %>%
ggplot(aes(hour_pick, n, color = weekday)) +
geom_line(size = 1.5) +
labs(x = "hour of the day", y = "count")
plot(weekday_hour_pickup)
Upvotes: 3
Views: 1570
Reputation: 47008
First, to simulate what your data might look like
TIMES = seq(from=mdy_hm("May 11, 1996 12:05"),
to=mdy_hm("May 18, 1996 12:05"),length.out=10000)
days.of.week <- weekdays(as.Date(4,"1970-01-01",tz="GMT")+0:6)
n = 1000
set.seed(100)
i = sample(1:length(TIMES),n)
my_data <- data.frame(
new_pickup=TIMES[i],
weekday = weekdays(TIMES[i])
)
Before you do plot, you need to factor the weekday variable in the correct order:
my_data$weekday <- factor(my_data$weekday,levels=days.of.week)
Then we set the color, in this case I set the extremes to be black and firebrick. You might needa play around with this
COLS <- alpha(colorRampPalette(c("black","firebrick"))(7),0.6)
names(COLS) <- days.of.week
Then we plot
weekday_hour_pickup <- my_data %>%
mutate(hour_pick = hour(new_pickup))%>%
group_by(hour_pick, weekday) %>%
count() %>%
ggplot(aes(hour_pick, n, color = weekday)) +
geom_line(size = 1) +
labs(x = "hour of the day", y = "count")+
scale_color_manual(values=COLS) +
theme_bw()
Not a very nice plot because I don't have your data, but you can adjust the COLS to get the contrast you need.
Upvotes: 1
Reputation: 7858
This a good option to make your descrite values as if they have a gradient
# call libraries
library(dplyr)
library(ggplot2)
# define weekdays
weekdays <- c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
# define 7 colours from black to red
colours <- scales::seq_gradient_pal(low = "#000000", high = "#ff0000", space = "Lab")(1:7/7)
# create values for scale colour manual
values <- setNames(colours, weekdays)
# create fake data
data <- tibble(hour_pick = rep(1:24, 7),
n = rnorm(7*24) + rep(1:7, each = 24),
# weekday must be a factor if you want your legend to be sorted!
weekday = factor(rep(weekdays, each = 24), levels = weekdays, ordered = TRUE))
ggplot(data) +
geom_line(aes(x = hour_pick, y = n, colour = weekday)) +
theme_light() +
scale_colour_manual(values = values)
Upvotes: 2