user3083324 - 2 months ago 19

R Question

How to draw multiples polygonal chains in ggplot? I was writing something like:

`x=c(1,3,4,5,6)`

y=c(0.5,2,3,7,1)

z=c(8,2,6,7,8)

n=length(x)-1

library(ggplot2)

p <- ggplot(mtcars, aes(wt, mpg))

for (i in 1:n){

p <-p + geom_segment(aes(x = x[i], y = y[i], xend = x[i+1], yend = y[i+1]), colour = "red")

p$plot_env <- list2env(list(x=x,y=y))

}

Drawing two polygonal chains:

`n=length(x)`

pol1=c(x,y)

pol2=c(y,z)

g=c(rep(1,n),rep(2,n))

library(ggplot2)

p0 <- ggplot(mtcars,aes(wt,mpg))

p0 + geom_path(aes(pol1,pol2,group=g),data=data.frame(pol1,pol2))

Answer

I can't quite tell what you want here.

- Are you specifying more than one path? I only see a single set of
`x`

and`y`

values. - What is
`z`

supposed to be doing?

You can draw a single (unclosed) path via

```
p0 <- ggplot(mtcars,aes(wt,mpg))
p <- p0 + geom_path(aes(x,y),data=data.frame(x,y))
```

Or a closed path via

```
p0 + geom_polygon(aes(x,y),data=data.frame(x,y),fill=NA,
colour="black")
```

If you do have more than one path, you can combine all the vertices in two long vectors `x`

and `y`

, make up a `g`

vector to distinguish paths, and use `aes(x,y,group=g)`

to get the paths/polygons drawn separately.