1

I'm trying to plot some data using geom_line in ggplot. However, I'd like to set the y-variable as continuous rather than the x-variable. (my data is regarding the concentration of nutrients at different depths in a lake, so it makes more sense if the continuous depth variable is on the y axis).

Here is some faux data.

library(ggplot2)
library(dplyr)
library(tidyr)
depth <- c(-2, -4, -6, -8, -10, -12, -14)
nutrient1 <- c(1, 1, 3, 1, 5, 1, 3)
nutrient2 <- c(2, 2, 4, 2, 8, 9, 3)
data <- as.data.frame(cbind(depth, nutrient1, nutrient2))
data.gathered <- data %>%
gather(key = nutrient, value = value, 2:3)

Here is my attempt at plotting that. The negative value for y is only to indicate the depth below something.

ggplot(data.gathered, 
       aes(x = value, y = depth, colour = nutrient)) + 
    geom_line()

If I plot it this way, I get the continuous line defined by the x-value (the nutrient values). I want the line to connect my points in an order defined by the y-values, rather than the x-values. So, the line for nutrient1 should progress as 1,-2 -> 1,-4 -> 3, -6 -> 1, -8 and so on. It seems like it should be easy, but I've been struggling.

Does anyone know how to fix this?

Thanks!

alistaire
  • 42,459
  • 4
  • 77
  • 117
  • 1
    Either use `geom_path` instead of `geom_line` (as long as your dataset is in order), or switch x and y and use `coord_flip`, e.g. `ggplot(data.gathered, aes(x = depth, y = value, colour = nutrient)) + geom_line() + coord_flip()` – alistaire May 23 '17 at 17:32
  • Alistaire is right. Ran into this a while ago. The geom_path is the way to go. If you want more code let me know. Bill `ggplot(toolik.df, aes(x=temp_c, y=depth)) + geom_point(color = "darkblue")+ geom_path(color = "darkblue")+ geom_segment(aes(x = 0, xend = 18, y = 5, yend = 5))+ annotate("text", x=2, y=6.5, label= "thermocline")+ scale_x_continuous( position = "top", limits=c(0,18))+ scale_y_reverse()+ ylab("Depth (m)") ` – Bill Perry May 23 '17 at 22:26

0 Answers0