Rspacer
Rspacer

Reputation: 2429

How to create stack bar charts that look cubic (3D) in R ggplot2?

I want the stack charts as coded below but I want them to look cubic (attached). Is it even possible in R?

set.seed(123)
specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3))
condition <- rep(c("normal" , "stress" , "Nitrogen", "T") , 3)
value <- abs(rnorm(12, 0 ,15))
data <- data.frame(specie,condition,value)
 
# Stacked
ggplot(data, aes(fill=condition, y=value, x=specie)) + 
    geom_bar(position="stack", stat="identity", alpha = 0.7, width = 0.3) + theme_classic()

enter image description here

enter image description here

Upvotes: 2

Views: 599

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

This is possible with the unpublished ggrgl package, among others. Applying this to your example, we have:

remotes::install_github('coolbutuseless/devout')
remotes::install_github('coolbutuseless/devoutrgl')
remotes::install_github('coolbutuseless/ggrgl', ref='main')

library(rgl)
library(devout)
library(devoutrgl)
library(ggrgl)
library(ggplot2)

p <- ggplot(data, aes(fill=condition, y=value, x=specie, z =2,
                 extrude_face_fill = condition)) + 
    geom_bar_z(position="stack", stat="identity", width = 0.3, extrude = TRUE,
               color = "black") + 
  theme_classic()

devoutrgl::rgldev()
p
invisible(dev.off())

The result is a rotatable 3D ggplot:

enter image description here

Upvotes: 5

Related Questions