Home > other >  plot the values of list in df in r
plot the values of list in df in r

Time:10-30

suppose i have the following df

dataset values
1 c(1,3,4,5,2)
2 c(7,8,1,2,3)
3 c(4,11,10,3,2)

I want a graph with x axis numbers 1 to 5 corresponding to the size of the list of values, and in y axis the list values. The resulting graph must have 3 different lines corrsponding to each dataset.

I'm trying with

    ggplot(df,aes(x=c(1:5),y=values,color=dataset)   geom_line()

but i have this error : Error: Aesthetics must be either length 1 or the same as the data (3): x and y

the problem is that is taking y as length 1 list.

CodePudding user response:

You may unnest the data, create the x column and then plot -


library(tidyverse)

df %>%
  unnest(values) %>%
  group_by(dataset) %>%
  mutate(x = row_number(), 
         dataset = factor(dataset)) %>%
  ungroup %>%
  ggplot(aes(x, values, color = dataset))   geom_line()

enter image description here

data

It is easier to help if you provide data in a reproducible format

df <- structure(list(dataset = 1:3, values = list(c(1, 3, 4, 5, 2), 
    c(7, 8, 1, 2, 3), c(4, 11, 10, 3, 2))), 
row.names = c(NA, -3L), class = "data.frame")
  •  Tags:  
  • r
  • Related