Search code examples
rggplot2plotlyr-plotly

How to toggle between linear and logrithmic scale for a stacked bar chart using R, ggplot and plotly?


I want to provide user option to toggle between linear and logarithmic scale for stacked bar chart. I have found example for a line chart and i have tried to repurpose it but could not change it to fit my requirement of stacked bar chart.

Following is the sample data:

    Vcc_cost <-  c("Health", "risk", "herd")
    Procurement_cost <- c(108898.3, 6847515.7, 171187893.0)
    Delivery_cost <- c(27224.58, 1711878.93, 42796973.25)

    sample_data <- data.frame(Vcc_cost, Procurement_cost , Delivery_cost)

Following is the way i am trying to plot it:

fig <- plot_ly(sample_data, type = 'bar') %>% 
  add_trace(x=~Vcc_cost, y=~Procurement_cost,  name = "Procurement Cost") %>% 
  add_trace(x=~Vcc_cost, y=~Delivery_cost, name="Delivery cost", visible = F)

fig <- fig %>%  layout(barmode = 'stack',
                       updatemenus = list(list(
                         active = 0,
                         buttons= list(
                           list(label = 'linear',
                                method = 'update',
                                args = list(list(visible = c(T,F)), list(yaxis = list(type ='linear')))),
                           list(label = 'log',
                                method = 'update', 
                                args = list(list(visible = c(F,T)), list(yaxis = list(type ='log'))))))))

However the the linear dropdown gives me "Delivery Cost" and the log dropdown gives me "Procurement cost". But, i want to get the stacked bar where only the y-axis changes from linear scale to log scales (based on the dropdown selection). I found the following link on how to toggle between log and linear scale for a line chart and i have tried to use this but i am not able the get the result that i want:

Interactively change axis scale (linear/log) in Plotly image using R

I am attaching the picture of the results that i get when i select different dropdowns:

When i select "Linear" scale:

When i select "log" scale:

I will really appreciate if someone can guide me in the right direction. Thank you.


Solution

  • Try changing both the visible = c(T,F) and the visible = c(F,T) to visible = c(T,T) and see if that helps!