我正在尝试使用 R 创建数据表 迷你图,并将其用于我闪亮的信息中心。 简化的测试数据如下:
#Create lists for test df
Employee_name <- c('Alice',"Alice", "Alice", 'Brian', "Brian", "Brian","Brian",'Carol', 'Carol', 'Dan', 'Dan','Dan', 'Dan','Dan','Dan', "Lily", "Lily", "Eric", "Eric")
Product_type <- c('A', "A", "A", "A", "L",'L',"L", "A", "L", "A", "A", "A",'L', "L", "L", "R", "A", "I", "I")
Project_status <- c("Closed", "Legacy","Active","Closed", "Active", "Dropped", "Closed","Closed","Closed","Closed","Active","Dropped","Active","Closed","Dropped", "Active", "Closed", "Active", "Closed")
Proj_count_byTypeStatus <- c(2,1,1,4,12,1,4,3,2,10,3,1,3,8,1,8,1, 2,1)
#Test Data Frame
test_df <- data.frame(Employee_name, Product_type, Project_status, Proj_count_byTypeStatus)
如何将df变成这样的东西(而不是java,使用R代码):https://www.highcharts.com/demo/sparkline
更具体地说:
答案 0 :(得分:3)
终于想出办法来实现它。
在这种情况下的基本想法是:
代码如下:
library(DT)
library(sparkline)
library(dplyr)
library(htmlwidgets)
library(reshape2)
library(data.table)
#df preparation
sparkline_df_2 <- test_df %>%
mutate(Project_status = as.character((Project_status), labels=c('Active',
'Closed', 'Dropped', 'Legacy'))) %>%
group_by(Employee_name, Product_type) %>%
mutate(Prod_total= sum(Proj_count_byTypeStatus)) %>%
complete(Project_status = c('Active', 'Closed', 'Dropped', 'Legacy'), fill = list(Proj_count_byTypeStatus = 0)) %>%
as.data.frame() %>%
group_by(Employee_name, Product_type) %>%
summarize(Project_status = paste0(Proj_count_byTypeStatus, collapse = ","))
sparkline_df2_spread <- dcast(sparkline_df_2, Employee_name ~ Product_type)
#DT configuration
colDefs <- list(list(className = 'dt-center',targets = c(1:4), render = JS("function(data, type, full){ return '<span class=spark>' + data + '</span>' }")))
bar_string <- "type: 'bar', colorMap: ['#27AE60', '#48C9B0', '#C39BD3', '#F4D03F'], width: 50, height: 25, barWidth: 20, barSpacing:5, highlightColor: 'orange', tooltipFormat: '{{offset:levels}} : {{value}}', tooltipValueLookups: { levels: { '0': 'Active', '1': 'Closed', '2': 'Dropped', '3': 'Legacy' }}"
sl_bar <- JS(sprintf("function (oSettings, json) { $('.spark:not(:has(canvas))').sparkline('html', {%s})}", bar_string))
d2 <- datatable(data.table(sparkline_df2_spread),
rownames = FALSE,
options = list(columnDefs = colDefs,
fnDrawCallback = sl_bar))
d2$dependencies <- append(d2$dependencies, htmlwidgets:::getDependency("sparkline"))
d2
希望这对有需要的人有所帮助。 :)
答案 1 :(得分:0)
我们可以使用library (ggplot2)
和facet_grid
为每个prodcut_type
创建一个单独的条形图。你可以将Employee_name
放在x轴上,Proj_count_byTypeStatus
放在y轴上
library(ggplot2)
ggplot(test_df, aes(x = Employee_name, y = Proj_count_byTypeStatus, fill = Project_status)) +
geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ Product_type)
,输出结果为: