Would like to know if it is possible to make a geom_line be red when it's between sept-feb and blue for the rest of the months?
Asked
Active
Viewed 148 times
0

P_S_13
- 65
- 3
-
It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 15 '22 at 20:09
-
1Possible duplicate: https://stackoverflow.com/questions/47498588/ggplot-line-plot-different-colors-for-sections/47498831 – MrFlick Feb 15 '22 at 20:09
-
1Possible duplicate: https://stackoverflow.com/questions/55756336/change-color-for-just-part-of-a-line – MrFlick Feb 15 '22 at 20:10
1 Answers
0
Yes, it's possible. The easiest way to do it by creating a vector of your colors, the same length as the rows in your dataframe, and passing it to the col
argument in geom_line()
.
Here is an example:
library(dplyr, warn.conflicts = FALSE)
library(ggplot2)
library(lubridate, warn.conflicts = FALSE)
# create some dates and values
df <- tibble(
date = today() + seq(from = -365, to = 0, by = 30),
value = runif(length(date), min = 300, max = 800)
)
df %>%
ggplot(aes(x = date, y = value)) +
geom_line(
col = ifelse(month(df$date) %>% between(3, 8), "blue", "red")
) +
geom_point()

jpiversen
- 3,062
- 1
- 8
- 12
-
seem to get an error message when I try to reproduce it with my df `Error: Aesthetics must be either length 1 or the same as the data (81): colour` – P_S_13 Feb 15 '22 at 20:53
-
You need to make sure the vector is the same length as your data - as stated in the answer. Edit this part of the code to make a vector of `red` and `blue`s the same length as your df: `ifelse(month(df$date) %>% between(3, 8), "blue", "red")` – jpiversen Feb 15 '22 at 20:58
-
2If you update your question with some data, we might be able to help you better @P_S_13. – jpiversen Feb 15 '22 at 21:22