1 year ago
#323070
Angela Malzow
R - Filled area using geom_rect or annotate rect, returning errors
I'm trying to create a colored/shaded horizontal band across my graph in RStudio. I want the filled band between 60 and 100 on the y axis, the entire length of the x axis.
x axis is a date range y axis is numerical
Here's my Data set
I've tried a few different things, such as geom rect and annotate rect, and I think I know why I'm receiving the errors but I don't know how to work the code differently to make it work. I would prefer a filled area over the annotate, but at this point, whichever works is a good start.
You can probably tell, I'm an infant in R.
Here's my working code and resulting visual:
# load libraries
library(tidyverse)
library(viridis)
# set theme
theme_set(
theme_classic() +
theme(legend.position = "right", axis.text.x = element_text(angle = 90)))
# load data
heartrates_vis1 <- read_csv("/Documents/R/Casestudy_Bellabeat/cleaned_data/fitbit_hr_min_max_per_id_date_2.csv")
pal <- c(
"2022484408" = "aquamarine",
"2026352035" = "blue",
"2347167796" = "blueviolet",
"4020332650" = "chartreuse",
"4388161847" = "coral",
"4558609924" = "cornflowerblue",
"5553957443" = "cyan",
"5577150313" = "darkgoldenrod",
"6117666160" = "cadetblue",
"6775888955" = "burlywood4",
"6962181067" = "chocolate1",
"7007744171" = "darkgreen",
"8792009665" = "firebrick",
"8877689391" = "darkseagreen"
)
heartrates_vis1 %>%
ggplot(mapping = aes(x = date, y = meanhr, color = factor(id))) +
geom_point() +
scale_x_date(date_labels = "%b %d", date_breaks = "1 day") +
scale_color_manual(
values = pal) +
labs(title = "bellabeat Case Study: Insights from FitBit Heart Rate Readings",
subtitle = "Daily Averages per Participant from April 12-May 12, 2016",
caption = "\n Data source: Kaggle user - Möbius\n Link: https://www.kaggle.com/datasets/arashnic/fitbit",
color = "Session id",
x = "HR Reading Date",
y = "Average of Daily Readings")
I tried to add (with and without 'mapping =':
+ geom_rect(mapping = aes(xmin = -Inf, xmax = Inf, ymin = 60, ymax = 100, alpha = 1/5, fill = "aliceblue"))
And received the following error:
Error: Invalid input: date_trans works with objects of class Date only
I then tried to add:
+
annotate("rect", xmin = "2016-04-11", xmax = "2016-05-13", ymin = 60, ymax = 100, alpha = .2, fill = "blue")
And again received the same error:
Error: Invalid input: date_trans works with objects of class Date only
I'd like to get something like this gray area fill (my same dataset in Tableau):
Thanks!
r
date
shapes
annotate
geom
0 Answers
Your Answer