Reputation: 7517
In my data
I have 12 columns called X1
to X12
plus one additional column called x
. Using ggplot2
package, I was wondering how to plot each of the columns X1
to X12
as the y-axis, against the same x
column as the x-axis?
I suspect I need a facet_wrap()
for each of X1
to X12
as the y-axis, and x
as the x-axis. So we will have 12 plots each with one of X1
to X12
as the y-axis, and the same x
column as the x-axis.
Note: I need a geom_line
.
library(tidyverse)
data <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/vp_cond.csv')
long <- pivot_longer(data, everything()) # do we need to do this before plotting?
Upvotes: 0
Views: 1066
Reputation: 887951
We can use geom_line
with facet_wrap
library(ggplot2)
data %>%
pivot_longer(cols = -x) %>%
ggplot(aes(x, value)) +
geom_line() +
facet_wrap(~ name)
Upvotes: 1
Reputation: 33812
Yes, you can use pivot_longer
(or gather
) and facets to achieve this.
One issue is that by default the labels will not be in the order X1 - X12, so you will need to specify the factor levels.
Try this:
data %>%
pivot_longer(cols = 1:12) %>%
mutate(name = factor(name, levels = paste0("X", 1:12))) %>%
ggplot(aes(x, value)) +
geom_line() +
facet_wrap(~name) +
theme_bw()
Result:
Upvotes: 1