helgasoft / echarty

Minimal R/Shiny Interface to ECharts.js
https://helgasoft.github.io/echarty/
87 stars 3 forks source link

How to make a 3d stacked bar chart? #38

Closed kkami1115 closed 1 month ago

kkami1115 commented 1 month ago

I would like to know how to create a 3D stacked bar chart similar to the example provided here: Bar 3D Example. Could you provide guidance or a code example to achieve this?

helgasoft commented 1 month ago

Sure - not too difficult. Data remains the same, only name 'matrix'(an R datatype) is changed to 'df'. We load the 3D plugin. The axes are type 'value' by default, so they need to be redefined as 'category'. Columns are already positioned in default order x,y,z, so no need for encode.

v <- LETTERS[1:10]
df <- data.frame(
  x = sample(v, 300, replace = TRUE), 
  y = sample(v, 300, replace = TRUE), 
  z1 = rnorm(300, 10, 1),
  z2 = rnorm(300, 10, 1),
  stringsAsFactors = FALSE
) |> 
  dplyr::group_by(x, y) |> 
  dplyr::summarise(
    z1 = sum(z1),
    z2 = sum(z2)
  ) |> 
  dplyr::ungroup() 

trans <- list(opacity = 0.4) # transparency
emphasis <- list(itemStyle = list(color = "red"))

library(echarty)
df |> ec.init( load='3D',  legend= list(show=T),
   xAxis3D = list(type='category'), 
   yAxis3D = list(type='category'),
   series= list(
    list(type='bar3D', stack= "stack", name= "Serie 1", itemStyle= trans, emphasis= emphasis),
    list(type='bar3D', stack= "stack", name= "Serie 2", itemStyle= trans, emphasis= emphasis) 
   )
)
kkami1115 commented 1 month ago

Thanks! I wasn’t sure where to start, so I decided to ask. While I’m at it, could I ask one more question? Is there a way to overlay an image on the XY plane of this graph? I’m not too familiar with ECharts, but if there’s such a feature, it would be great if you could point me in the right direction.

helgasoft commented 1 month ago

would be great if you could point me in the right direction.

take a look at 3D surface texture. Any 3D surface can have a texture applied on top and the texture could be defined as an image URL.

helgasoft commented 1 month ago

@kkami1115, the stacked bar code above has a problem with legend due to a newly discovered ECharts 3D bug. Here is updated code to avoid the bug

ser1 <- list(type='bar3D', stack= "stack", name= "Serie 1", itemStyle= trans, emphasis= emphasis)
ser2 <- ser1; ser2$name <- 'Serie 2';
df |> echarty::ec.init( load='3D',
   xAxis3D= list(type= 'category'), 
   yAxis3D= list(type= 'category'),
   series= list(ser1, ser2),
   legend= list(show= T)
) |> ec.upd({  # avoid legend bug in ECharts https://github.com/ecomfe/echarts-gl/issues/538
   dataset[[1]]$dimensions <- NULL
   dataset[[1]]$sourceHeader <- FALSE
   dataset[[1]]$source[[1]] <- NULL
})