echarts4r icon indicating copy to clipboard operation
echarts4r copied to clipboard

Automatic scaling in e_bar

Open svenb78 opened this issue 3 years ago • 2 comments

Hi,

given the example below:

df_01 <- data.frame(
  date = c("2022", "2021")
  , value = c(11000000, 15000000)
)

plot_e <- df_01 %>%
  echarts4r::e_chart(x = date) %>%
  echarts4r::e_bar(serie = value)

plot_e

Is there a simple way for an "automatic" scaling of the y-axis, without using something like dplyr::mutate(value = value / 1e6)?

Background: I use e_charts within a shiny app with multiple filters on hierarchical data. At the top level with few filters, the values are about millions, and the y-axis labels become quite long. Scaling them using the mutate example leads to the problem, that on a low level with many filters, the values get small and are printed with a lot of decimal places.

svenb78 avatar Sep 08 '22 00:09 svenb78

The simple way is Y-axis scale

data.frame(
	date = c("2022", "2021")
	,value = c(11000000, 15000000)
) |>
	e_chart(x = date) |>
	e_bar(serie = value) |>
	e_y_axis(scale= TRUE, min= 10000000) |> 
	e_grid(containLabel= TRUE)

image

helgasoft avatar Sep 08 '22 20:09 helgasoft

Hi,

thanks, but your proposal does not solve the problem which is the large number of zeros / digits at the y-axis ticks / labels. If I manually "down scale" the values, for example by using dplyr::mutate(value = value / 1e6), I get rid of the zeros in that case, but if the values become small as a result of filtering (-> shiny), I get axis ticks like 0.00001 and again too many digits.

So, what I'm looking for is an option which automatically recognizes the number of digits and scales the labels accordingly. Means: If value = 15000000 the label should be something like 15 Mio.. If value = 10 it should be 10.

What I found so far is that function (-> Link ):

comprss <- function(tx) { 
  div <- findInterval(as.numeric(gsub("\\,", "", tx)), 
                      c(0, 1e3, 1e6) )  # modify this if negative numbers are possible
  paste(round( as.numeric(gsub("\\,","",tx))/10^(3*(div-1)), 2), 
        c("","Tsd.","Mio.")[div] )}

With the help of comprss , I can modify df_01 as follows:

df_01$scaled_value <- comprss(df_01$value)

Now, I have a column with nicely scaled values, but they are character and I can use them only like that:

plot_e <- df_01 %>%
  echarts4r::e_charts(x = date) %>%
  echarts4r::e_bar(serie = value, bind = scaled_value, label = list(show=TRUE, formatter = "{b}"))

plot_e

The y-axis labels stay unaffected and my problem is not solved.

Ann.: So far, I helped myself by hiding the y-axis labels, but that is not what I actually want. :-)

svenb78 avatar Sep 08 '22 21:09 svenb78