Search code examples
rggplot2ggplotly

ggplot bar graph - changing colour for value of y


im new to stackoverflow and need some help please. I wanted to colour y (Value) data above a level of 1.35 and cant seem to get it to work. wanted Steelblue for below 1.35 and plum for above 1.35. Below is working graph minus the colour change.

dataframe i have is

Timestamp  Value 
20/10/2021 1.56
21/10/2021 1.426
22/10/2021 1.344
23/10/2022 1.23
24/10/2022 1.11

water$Timestamp <- water$Timestamp %>% dmy
river <- ggplot() + 
  coord_cartesian() +
  layer(
    data = water,
    mapping = aes(x = Timestamp, y = Value),
    stat = "identity",
    geom ="point", 
    position = position_identity()
  ) +
  layer(
    data = riverwater,
    mapping = aes(x = Timestamp, y = Value),
    stat ="identity",
    geom ="line",
    position = position_identity()
  )
ggplotly(river)

This is the example of non continuous graph of the 2 plots, one line and other point enter image description here


Solution

  • I simulated some data here to help make a plot more like your real case.

    To get the colors assigned by the Value you need to assign color inside aes(). geom_line() takes a group aesthetic which defines which data points are connected. If you specify a categorical aesthetic like color = Value > 1.35 then the group aesthetic will inherit from there and split into 2 lines. If you want to connect all the data points, you simply have to set group = 1 to specify that you want them all connected together.

    There are a few stylistic things in your code I'd also suggest to change:

    • It looks like you're plotting data from two separate data.frames into one graph. Usually it's better to merge/rbind those data somehow into a single data.frame before trying to incorporate into a single plot.
    • Your {ggplot2} syntax is a bit unusual. Usually if you're using the same aesthetics in multiple layers it's more efficient to specify those within the ggplot(aes(x = ..., y = ..., color = ...)) call to avoid repeating yourself. Also the layers are usually added by explicitly calling the geom_* or stat_*` of interest (as you can see in my code here). That said, your code is technically correct and will produce the desired plot with some small tweaks.
    library(tidyverse)
    library(lubridate)
    
    set.seed(8)
    d <- data.frame(Timestamp = seq(ymd("2021-10-20"), ymd("2022-10-24"), by = "days"),
                    Value = 1.35 + cumsum(runif(370, -1, 1)))
    
    d %>% 
      ggplot(aes(x = Timestamp, y = Value, color = Value > 1.35)) +
      geom_point() +
      geom_line(aes(group = 1)) +
      scale_color_manual(values=c("Steel blue","plum"))
    

    Created on 2022-10-26 with reprex v2.0.2