高度与R中数据相关的三角形

Vas*_*sim 2 visualization r

我的数据集

在此输入图像描述

我的要求

在此输入图像描述

基本上,我需要一个简单的三角形图表,其中高度是No column和Group Name in框中的值.宽度可以是任何尺寸.如果我们可以为不同的套装提供不同的颜色,那就太棒了.

我是新来的R,并试图polygon,lapply,geom_polygon,triangle,pascal triangle,ade4,pyramid和其他人,但没有成功.

此外,在R Studio中,这应该是视觉效果,而不是观看者视觉效果.

dan*_*son 5

我找不到一个好的包装,但我能够制作情节.对不起,我不使用R Studio,所以我不确定你的最后一点意味着什么.

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述