JohnCoene / echarts4r

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

Dynamic totals in barchart #647

Open alearrigo opened 3 hours ago

alearrigo commented 3 hours ago

Probably skill issue more than library issue.

I have a Shiny app example using echarts4r to visualize sales data by category and year.

I'm trying to add two features to this plot:

A dynamic total displayed at the top of the chart that updates based on the legend selection. I know how to create one but I don't know how to make it change when something in the legend gets deselected. I think I need some sort of reactive function that listens to selection and compute totals again?

A number on the right side of the bars showing the sum of categories, which also updates with the legend selection.

Here's my current code:

library(shiny)
library(echarts4r)
library(dplyr)

# Sample data
data <- data.frame(
  Year = rep(c("2020", "2021", "2022"), each = 4),
  Category = rep(c("Electronics", "Clothing", "Books", "Home"), 3),
  Sales = c(300, 200, 150, 250,
            350, 220, 180, 280,
            400, 250, 200, 320)
)

ui <- fluidPage(
  titlePanel("Sales by Category and Year"),
  mainPanel(
    echarts4rOutput("plot", height = "500px")
  )
)

server <- function(input, output, session) {
  output$plot <- renderEcharts4r({
    data %>%
      group_by(Year) %>%
      e_charts(Category) %>%
      e_bar(Sales, stack = "stack") %>%
      e_x_axis(axisLabel = list(interval = 0, rotate = 0)) %>%
      e_y_axis(splitLine = list(show = FALSE)) %>%
      e_labels(position = "inside") %>%
      e_tooltip(trigger = "axis") %>%
      e_legend(orient = "horizontal", bottom = "bottom", type = "scroll") %>%
      e_flip_coords()
  })
}

shinyApp(ui, server)

In the image what I need. Problem 1 is the total on top of the plot, Problem 2 are the numbers on the right side of the plot

immagine
JohnCoene commented 3 hours ago

Did you look into the events

You should be able to

observeEvent(input$plot_legend_change, {})

# and / or

observeEvent(input$plot_legend_selected, {})
alearrigo commented 3 hours ago

Did you look into the events

You should be able to

observeEvent(input$plot_legend_change, {})

# and / or

observeEvent(input$plot_legend_selected, {})

I'm going to look into it. Thanks for the quick reply! This is my first project using charts. Do you also know how to create the totals on the right side of the plot?

JohnCoene commented 2 hours ago

I'm not sure I understand where you want the total to go.

alearrigo commented 2 hours ago

In the attached images I need to compute the red numbers for each bar (850, 530,...). An extra label that is the sum of the label printed.

I think it's the same issues of: https://github.com/apache/echarts/issues/17649