我有一个如下所示的数据框:
## Data
df <- data.frame(label = c("A", "B", "C", "D"),
color = c("red", "red", "blue", "green"),
y = c(10, 11, 12, 13))
“A”和“B”属于同一类别,而“C”和“D”属于不同类别。
我想在图表上添加带有类别标签的图例。
## Highchart without Legend
## Basic highchart
h <- rCharts:::Highcharts$new()
h$chart(type = "column")
## Highchart data:
h$series(showInLegend = FALSE, data = rCharts::toJSONArray2(df[, c("label", "color", "y")], json = FALSE, names = TRUE))
## Highchart options:
h$xAxis(categories = unique(df$label), labels = list(rotation = 0, align = 'center', style = list(fontSize = '12px', fontFamily = 'Verdana, sans-serif')), replace = FALSE)
h$tooltip(formatter = "#! function() {return this.x + ': ' + this.y; } !#")
h$plotOptions(series = list(color = df$color), column = list(grouping = FALSE))
h # display highchart
我还没有找到任何有意义的方法来解决这个问题。
如有任何帮助,我们将不胜感激。
最佳答案
免责声明:我知道问题是rCharts
,我只是想使用 highcharter 包添加替代方案。
就像@Optimus所说,问题是添加多个系列。如果您有任意数量的系列(示例中的颜色)并希望自动添加它,您可以使用 highcharter
允许您使用 hc_add_series_list
函数从数据系列列表中添加多个系列。
library(highcharter)
library(dplyr)
df <- data_frame(label = c("A", "B", "C", "D"),
color = c("red", "red", "blue", "green"),
y = c(10, 11, 12, 13),
x = c(1:4)-1)
head(df)
series <- df %>%
group_by(color) %>% # each serie is from one color
do(data = list.parse3(.)) %>%
ungroup() %>%
mutate(name = paste("I'm color", color)) %>%
list.parse3()
这里list.parse3
与toJSONArray2
类似。
series[[1]]
$color
[1] "blue"
$data
$data[[1]]
$data[[1]]$label
[1] "C"
$data[[1]]$color
[1] "blue"
$data[[1]]$y
[1] 12
$data[[1]]$x
[1] 2
$name
[1] "I'm color blue"
最后:
highchart() %>%
hc_chart(type = "column") %>%
hc_add_series_list(series) %>%
hc_xAxis(categories = df$label) %>%
hc_plotOptions(column = list(grouping = FALSE))
结果将是:
关于r - rCharts 中的自定义图例(highcharts),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28370146/