rbeginner
rbeginner

Reputation: 41

Create time course plot from tibble

I am sorry because this feels like it has a really obvious answer, but I am new to tidyverse and ggplot and I can't seem to find a useful solution.

The output of my data is a tibble, where the first column is x, which I want on my x axis, and then follow multiple columns of y and z.

Dummy data:

t1 <- tibble(x = 1:5, y = 1, z = x ^ 2 + y)

I now want to have x as my x-axis, with y and z being lines with different colours in the same plot. I know that that works, if I put y and z as descriptors below each other next to the corresponding x values as:

t2 <- tibble(x = c(1:5,1:5), a = c(rep(1,5),c(2,5,10,17,26)), b = c(rep("y",5), rep("z",5)))
ggplot(data = t2, aes(x = x, y = a, group = b, color = b))+
geom_line()

Now I want to know if there is a way to have the same result with t1 or if there is a straightforward way to get to t2? Or do you have any pointers as to what I should search for?

Upvotes: 1

Views: 47

Answers (1)

stefan
stefan

Reputation: 125238

This could be achieved via tidyr::pivot_longer:

library(tidyverse)

t1 <- tibble(x = 1:5, y = 1, z = x ^ 2 + y)

t3 <- t1 %>% 
  pivot_longer(-x, names_to = "b", values_to = "a")

ggplot(data = t3, aes(x = x, y = a, group = b, color = b)) + geom_line()

Upvotes: 1

Related Questions