JohnCoene / echarts4r

🐳 ECharts 5 for R
http://echarts4r.john-coene.com/
Other
585 stars 82 forks source link

Stacked bar charts with facet #636

Open ammazzetto2 opened 1 week ago

ammazzetto2 commented 1 week ago

I am trying to create a stacked bar chart for two different companies, in different regions. See below a reproducible example:

library(dplyr)
library(echarts4r)

# Sample data for company X and Y 
total_X <- data.frame(
  region = factor(c("A", "B", "C")),
  Source_1 = c(5, 3, 6),
  Source_2 = c(7, 9, 1),
  Source_3 = c(3, 4, 8),
  company = "X"
)

total_Y <- data.frame(
  region = factor(c("A", "B", "C")),
  Source_1 = c(4, 7, 1),
  Source_2 = c(1, 5, 7),
  Source_3 = c(8, 3, 2),
  company = "Y"
)

# Merge data frames by region
test <- left_join(total_X, total_Y, by="region")

# Define a custom color palette as a named list
custom_colors <- list(
  Source_1 = "#1f77b4",   # blue
  Source_2 = "#ff7f0e",   # orange
  Source_3 = "#2ca02c"  # green
)

# Create the comparison chart with consistent colors
g_total_figure <- test %>%
  e_charts(region) %>%
  e_bar(Source_1.x, stack = "grp", name = "Source_1", itemStyle = list(color = custom_colors$Source_1)) %>%
  e_bar(Source_2.x, stack = "grp", name = "Source_2", itemStyle = list(color = custom_colors$Source_2)) %>%
  e_bar(Source_3.x, stack = "grp", name = "Source_3", itemStyle = list(color = custom_colors$Source_3)) %>%
  e_bar(Source_1.y, stack = "grp2", name = "Source_1", itemStyle = list(color = custom_colors$Source_1)) %>%
  e_bar(Source_2.y, stack = "grp2", name = "Source_2", itemStyle = list(color = custom_colors$Source_2)) %>%
  e_bar(Source_3.y, stack = "grp2", name = "Source_3", itemStyle = list(color = custom_colors$Source_3)) %>%
  e_tooltip(trigger = 'item', formatter = e_tooltip_item_formatter("decimal", digits = 2)) %>%
  e_toolbox_feature(feature = "saveAsImage") %>%
  e_legend(show = TRUE, textStyle = list(fontSize = 20)) %>%
  e_y_axis(
    name = "Source (kg)",
    nameLocation = "middle",
    nameRotate = 90,
    nameTextStyle = list(fontSize = 20),
    nameGap = 40,
    axisLabel = list(fontSize = 20)
  ) 

# Print the chart
g_total_figure

The figure below is what I get. image

It works, but I can't identify the companies (X and Y) in this Figure. I tried to use e_facet but couldn't figure it out how. What I was looking for was something similar to facet_wrap for ggplot2 that shows the facet (regions A, B and C in this case) and below the bar the name of the company (X and Y) for each region.

Any suggestions?