gpt4 book ai didi

r - Shiny :如何在数据表中显示条形图

转载 作者:行者123 更新时间:2023-12-05 07:48:55 25 4
gpt4 key购买 nike

我想在数据表中显示条形图。这link显示我想使用 javascript 做什么。我不了解 javascript 或 html,所以您能告诉我是否可以使用 shiny 实现此目的吗?

本站代码如下:

HTML代码:

<table id="dTable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Languages</th>
<th>Positive</th>
<th>Neutral</th>
<th>Negative</th>
</tr>
</thead>
<tbody>
<tr>
<td>English</td>
<td>50</td>
<td>20</td>
<td>25</td>
</tr>
<tr>
<td>German</td>
<td>25</td>
<td>10</td>
<td>12</td>
</tr>
<tr>
<td>French</td>
<td>20</td>
<td>20</td>
<td>17</td>
</tr>
<tr>
<td>Spanish</td>
<td>22</td>
<td>4</td>
<td>10</td>
</tr>
</tbody>
</table>

JavaScript:

$(function(){
$("#dTable").dataTable({
"columns": [
{
"title":"Languages"
},
{
"title":"Votes",
"render": function(data, type, row, meta){
return parseInt(row[1], 10) + parseInt(row[2], 10) + parseInt(row[3], 10)
}
},
{
"visible":false
},
{
"title": "Positive/Neutral/Negative",
"sortable":false,
"render": function(data, type, row, meta){
return $("<div></div>", {
"class": "bar-chart-bar"
}).append(function(){
var bars = [];
for(var i = 1; i < row.length; i++){
bars.push($("<div></div>",{
"class": "bar " + "bar" + i
}).css({
"width": row[i] + "%"
}))
}
return bars;
}).prop("outerHTML")
}
}
]
});
});

最佳答案

这就是您如何在 R shiny 中实现所提供的 Javascript 示例。

基本上,在执行renderDataTable时,需要在columnDefsrender选项中添加JS函数。

下面是示例代码-

# Prepare the Sample data
test_data <-
data.table(
Languages = c('English', 'German', 'French', 'Spanish'),
Positive = c(50, 25, 20, 22),
Neutral = c(20, 10, 20, 4),
Negative = c(25, 12, 17, 10)
)

# Define the Shiny UI and Custom CSS Elements
ui <- fluidPage(tags$head(tags$style(
HTML(
"
.bar-chart-bar {
background-color: #e8e8e8;
display: block;
position:relative;
width: 100%;
height: 20px;
}
.bar {
float: left;
height: 100%;
}
.bar1 {
background-color: green;
}
.bar2 {
background-color: yellow;
}
.bar3 {
background-color: red;
}
"
)
)), DT::dataTableOutput("test_table"))

# Rendering the DataTable in Shiny Server

server <- function(input, output) {
output$test_table <- DT::renderDataTable({
dt <- DT::datatable(
as.data.frame(test_data),
rownames = FALSE,
options = list(columnDefs = list(list(
targets = -1,
render =
JS(
"function(data, type, row, meta){
return $('<div></div>', {
'class': 'bar-chart-bar'
}).append(function(){
var bars = [];
for(var i = 1; i < row.length; i++){
bars.push($('<div></div>',{
'class': 'bar ' + 'bar' + i
}).css({
'width': row[i] + '%'
}))
}
return bars;
}).prop('outerHTML')
}"
)
)))
)
})
}

# Run the App
shinyApp(ui, server)

关于r - Shiny :如何在数据表中显示条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37967996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com