我尝试使用 echarts4r 库创建极坐标条形图,并且图表已正确生成。我的数据集中有 x、y 和 z 字段。要生成图表,我们只需要 x,y 字段。现在我想在工具提示中显示 x、y 和 z。 x 和 y 在工具提示中显示良好,但 z 值未定义。请参阅下面的示例代码:
library(echarts4r)
# create example dataset
df <- data.frame(x = c("A", "B", "C"), y = c(10, 20, 30), z = c("foo", "bar", "baz"))
# create polar bar chart
df %>%
e_charts(x) %>%
e_bar(y, coord_system = "polar") %>%
e_angle_axis(startAngle = 90, max = 150, axisLine = list(show = FALSE), axisTick = list(show = FALSE),
splitLine = list(show = FALSE), axisLabel = list(show = FALSE)) %>%
e_radius_axis(type = "category", data = df$x, axisLabel = list(interval =0,margin = 50, fontSize= 15, color = 'black'),
axisLine = list(show = FALSE), axisTick = list(show = FALSE), z = 10) %>%
e_polar() %>%
e_legend(show = FALSE) %>%
e_tooltip(formatter = htmlwidgets::JS("
function(params) {
return params.name + '<br>' + params.value + '<br>' + params.data.z;
}
"))
如何在工具提示中显示 z 值?
您首先必须将
z
的值包含到图表中。使用 e_add_nested()
这通常不是很困难,但是,与 e_polar()
结合使用似乎存在 bug。
为了让它工作,我使用了
fix_add_nested
函数,来自 this 非常好的答案。如果包含此内容,您可以使用 z
访问 params.data.itemStyle.z
值。
library(echarts4r)
# create example dataset
df <- data.frame(x = c("A", "B", "C"), y = c(10, 20, 30), z = c("foo", "bar", "baz"))
fix_add_nested <- function(e) {
e$x$opts$series[[1]]$data <- lapply(
e$x$opts$series[[1]]$data,
function(x) { names(x) <- c("value", "itemStyle"); x }
)
e
}
# create polar bar chart
df %>%
e_charts(x) %>%
e_bar(y, coord_system = "polar") %>%
e_angle_axis(startAngle = 90, max = 150, axisLine = list(show = FALSE), axisTick = list(show = FALSE),
splitLine = list(show = FALSE), axisLabel = list(show = FALSE)) %>%
e_radius_axis(type = "category", data = df$x, axisLabel = list(interval =0,margin = 50, fontSize= 15, color = 'black'),
axisLine = list(show = FALSE), axisTick = list(show = FALSE), z = 10) %>%
e_polar() %>%
e_legend(show = FALSE) %>%
e_add_nested("values", z) %>%
fix_add_nested() %>%
e_tooltip(formatter = htmlwidgets::JS("
function(params) {
return params.name + '<br>' + params.value + '<br>' + params.data.itemStyle.z;
}
"))