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.
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.
I am trying to create a stacked bar chart for two different companies, in different regions. See below a reproducible example:
The figure below is what I get.![image](https://github.com/JohnCoene/echarts4r/assets/95891986/905685f4-e6e8-4052-8ddd-d2f091dcb11f)
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?