Search code examples
rloopsfor-loopggplot2

Multiple polygons in one axis using ggplot


Im new in R programming, I want to plot multiple triangles in one chart. When I placed the ggplot command inside a for loop, it only resets the chart viewer.But I want to see all the plots in one plot simultaneously. Here's the code that I have been working on.

data<-read.csv("test.csv",sep=",",header=TRUE)
library("ggplot2")
for(i in 1:5){      
    D=data.frame(x=c(data$x1[i],data$x2[i],data$x3[i]),
    y=c(data$y1[i],data$y2[i],data$y3[i]))
    print(ggplot()+
        (geom_polygon(data=D, mapping=aes(x=x,y=y),col="blue")))
}

I hope you can help me.Many thanks


Solution

  • We can use the data.table package to keep our reshaping to one step as it allows us to specify patterns for measure-columns.

    First, we create an ID for each observation:

    dat$ID <- 1:nrow(dat)
    

    Then we create our data in long format. This is the best format for ggplot: each observation (or point) on it's own row.

    library(data.table)
    dat_m <- melt(setDT(dat),measure=patterns(c("^x","^y")),value.name=c("x","y"))
    

    Plotting is then easy:

    p <- ggplot(dat_m, aes(x=x,y=y,group=ID)) +
      geom_polygon()
    p
    

    enter image description here

    Data used:

    dat <- structure(list(x1 = c(1, 3, 5), x2 = c(2, 4, 6), x3 = c(1, 3, 
    5), y1 = c(1, 1, 1), y2 = c(1, 1, 1), y3 = c(2, 2, 2)), .Names = c("x1", 
    "x2", "x3", "y1", "y2", "y3"), row.names = c(NA, -3L), class = "data.frame")