Vasim - 1 year ago 101

R Question

My Dataset

My Requirement

Basically, I need a simple triangle chart where the height is the value in No column and Group Name in box. The width can be of any size. If we can have different colors for different sets it will be great.

I am new to R, and have tried

`polygon`

`lapply`

`geom_polygon`

`triangle`

`pascal triangle`

`ade4`

`pyramid`

Also, in R Studio this should be as a plot visual not in viewer visual.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

I could not find a good package for this, but I was able to make the plot. Sorry, I don't use R Studio, so I'm not sure what your last point means.

```
plot.pyramid <- function(df, hspace=2, colours=NA){
n <- nrow(df) #number of observations
#i don't know what you want to do with colors
if(any(is.na(colours))) colours <- rep('blue', n)
if(length(colours)<n) colours <- rep(colours,n)[1:n]
cum.height <- cumsum(df$no) #cumulative height. y coordinates in plot
max.cum.height <- max(cum.height) #max height of the graph
center <- max(cum.height)/2 #where to center the x values
#there are 2 y values per point to make the horizontal segments
y <- max.cum.height - rep(cum.height,2)
x <- c(center-cum.height/2, center + cum.height/2) #horizontal segments are same size as height, centered
x <- c(x, center) #add x-coord for tip
y <- c(y, max.cum.height) #add y-coord for tip
reorder <- order(y) #reorder points for convenience in 'for loop' below
y <- y[reorder]
x <- x[reorder]
plot(x,y,'n', xaxt='n', yaxt='n', ann = FALSE) #creates blank plot of correct size
for(i in 0:(n-1) ){
if(i != n-1) #if not tip
{
xcoords <- x[i*2+1:4][c(1,3,4,2)] #reorder the points slightly to get a trapezoid fill
ycoords <- y[i*2+1:4][c(1,3,4,2)]
#add the space between the trapezoids
ycoords[ycoords==min(ycoords)] <- ycoords[ycoords==min(ycoords)] + hspace
}else{
xcoords <- x[i*2+1:3] #triangle only has 3 points
ycoords <- y[i*2+1:3]
ycoords <- ycoords + hspace
}
polygon(xcoords,ycoords,col=colours[i+1]) #plot points and fill
text(mean(xcoords), mean(ycoords), cex=.8, paste(df$group[n-i], df$no[n-i]) ) #add text
}
}
df <- data.frame(group=c(paste0('Group-',seq(5))), no=c(5,25,36,40,50))
colours <- c('blue','green','blue','gray','green')
plot.pyramid(df, 2, colours)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**