Search code examples
rggplot2density-plot

Plotting values from multiple columns using ggplot


I have data.frame as follows

test=data.frame(start=rep("0",10),end=rep("100",10),Typ1=c("530","630","500","400","350","600","1032","378","430","567"),Type2=c("100","70","50","120","130","50","75","86","90","95"),Type3=c("10","50","40","22","13","45","15","36","19","20"))
>test
start end Type1 Type2 Type3
0     100  530   100    10
0     100  630    70    50
0     100  500    50    40
0     100  400   120    22
0     100  350   130    13
0     100  600    50    45
0     100 1032    75    15
0     100  378    86    36
0     100  430    90    19
0     100  567    95    20

All I want is to plot the above data frame with x-axis denoting the start and end and Y-axis denoting the Type1, Type2 and Type3. I tried the following code but it throwed me error

ggplot(test,aes(x=c(start,end)),y=c(Type1,Type2,Type3)) +geom_density()

Kindly guide me. Thanks in advance.


Solution

  • First, cast your data to long format (works better for ggplot), then plot

    I also created some x-values...

    library(data.table)
    library(ggplot2)
    plotdata <- setDT(test)[, x := seq(0,100,length.out = 10)]
    plotdata <- melt( setDT(test), id.vars = c("x"), measure.vars = patterns("^Typ"), value.factor = FALSE )
    
    ggplot( data = plotdata, 
        aes( x = value, 
             color = variable,
             fill = variable)
        ) + 
      geom_density()
    

    enter image description here