1

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

Liliputian
  • 55
  • 10
  • 1
    Hi, welcome to SO. Please consider reading up on [ask] and how to produce a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). It makes it easier for others to help you. – Heroka Feb 06 '16 at 11:17

2 Answers2

6

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")
Jaap
  • 81,064
  • 34
  • 182
  • 193
Heroka
  • 12,889
  • 1
  • 28
  • 38
1

Your code is creating a new ggplot() each loop. What you want is to split the plot command into multiple steps. First set p = ggplot() outside the for loop, then inside the for loop, add your polygons: p = p + geom_polygon(...). After the end of the for loop, call print(p) to see the result.

CPhil
  • 917
  • 5
  • 11
  • In ggplot when you're doing the same thing multiple times, it's generally not the way to go. It's probably easier solved with some reshaping of the data and a grouping-command. – Heroka Feb 06 '16 at 11:19
  • @Heroka Correct - it would be prettier to not use any for loops at all. The y1,y2,and y3 columns could be all one column, with an extra column to show which triangle they belong to. My answer was just minimising the amount of code edits required to get it to work. – CPhil Feb 06 '16 at 11:21