简体   繁体   中英

R ggplot multiple columns facet by similar column name

Bear with me here as I am new to R.

I have a data frame with many columns, some of them have similar names:

> df
  x1 x2  y1  z1  z2   z3
1  1  2 1.2 1.1 1.4  4.4
2  2  3 2.4 2.2 2.8  8.8
3  3  4 3.6 3.3 4.2 13.2
4  4  5 4.8 4.4 5.6 17.6
5  5  6 6.0 5.5 7.0 22.0
6  6  7 7.2 6.6 8.4 26.4
7  7  8 8.4 7.7 9.8 30.8

I want to plot all of the columns in the same figure, but each similar column name to be plotted in the same "facet" using ggplot. So for this there should be three sections, "x","y","z". Each facet should have a line for each column

Is there some type of ggplot solution using facet wrap?

Using some data wrangling to tidy your data you could do (where I assumed the x axis value should be the row number as you asked for a a line for each column ):

library(tidyr)
library(dplyr)
library(ggplot2)

dat_tidy <- dat |> 
  mutate(row = row_number()) |> 
  pivot_longer(-row) |> 
  extract(name, into = c("facet", "col"), "(.)(.)")

ggplot(dat_tidy, aes(row, value, color = col)) +
  geom_line() +
  facet_wrap(~facet)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM