styleColorBar 居中并根据符号向左/向右移动 [英] styleColorBar Center and shift Left/Right dependent on Sign
问题描述
我希望创建在使用 DT 的 datatable
时出现在列单元格中间并根据单元格中的值是正数还是负数向左或向右伸出的条.
I am looking to create bars that when using DT's datatable
appear in the middle of the cells of a column and reach out left or right depending on whether the value in the cell is positive or negative.
我尝试使用函数 styleColorBar
并将参数 backgroundPosition
更改为 'left'
或 'center'
> 然而,每次尝试时,条形仍然出现在单元格的右侧,并且总是向左移动.
I have tried using the function styleColorBar
and changing the argument backgroundPosition
to 'left'
or 'center'
however with each try the bars still appear to the right of the cell and always go to the left.
我无法从 R 代码中找到示例,但附上了可以在 Excel 上完成的示例;颜色不是必需的,但如果包括在内,那将是一个奖励.
I can't find an example from R code, but have attached an example of what can be done on Excel; the colours aren't necessary but if included that would be a bonus.
推荐答案
您可以创建一个使用 CSS 渐变的自定义 styleColorBar
函数(与原始 styleColorBar
相同)制作你想要的那种酒吧.
You could make a custom styleColorBar
function that uses the CSS gradients (same as the original styleColorBar
) to make the kind of bars you want.
这是一个例子(抱歉,长行,添加新行会破坏 CSS):
Here is an example (sorry for the long line, adding new lines breaks the 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))
}
使用一些测试数据:
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'))
这篇关于styleColorBar 居中并根据符号向左/向右移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!