StyleColorBar Center and left / right shift depending on the sign

I am looking to create bars that when using the DT datatable appear in the middle of the cells of the column and go left or right depending on whether the value in the cell is positive or negative.

I tried using the styleColorBar function and changed the backgroundPosition argument to 'left' or 'center' , however with each attempt the rows are still displayed to the right of the cell and always go to the left.

I can not find an example from the R-code, but attached an example of what can be done in Excel; colors are not needed, but if they are included, it will be a bonus.

enter image description here

+7
r shiny datatable dt
source share
1 answer

You can create a custom styleColorBar function that uses CSS gradients (the same as the original styleColorBar ) to make the bars you need.

Here is an example (sorry for the long line, adding new lines to break CSS):

 color_from_middle <- function (data, color1,color2) { max_val=max(abs(data)) JS(sprintf("isNaN(parseFloat(value)) || value < 0 ? 'linear-gradient(90deg, transparent, transparent ' + (50 + value/%s * 50) + '%%, %s ' + (50 + value/%s * 50) + '%%,%s 50%%,transparent 50%%)': 'linear-gradient(90deg, transparent, transparent 50%%, %s 50%%, %s ' + (50 + value/%s * 50) + '%%, transparent ' + (50 + value/%s * 50) + '%%)'", max_val,color1,max_val,color1,color2,color2,max_val,max_val)) } 

Using some test data:

 data <- data.frame(a=c(rep("a",9)),value=c(-4,-3,-2,-1,0,1,2,3,4)) datatable(data) %>% formatStyle('value', background=color_from_middle(data$value,'red','blue')) 

enter image description here

+14
source share

All Articles