我正在尝试创建一个条形图,其中x轴标签位于条形旁边。 我想要的结果将类似于:
(摘自:HighCharts Place Label on Bar)
但是,有两个区别:
我正在用R highcharter制作图表
我不要酒吧内的标签,但要放在标签旁边。它的外观应与通常在条形旁边添加值的方式类似,请参见for example:
我尝试过偏移标签,但是由于我不希望它们位于固定位置,而是相对于条形的位置,所以不起作用。
我也尝试过使用批注,但是对于这些批注我还不够熟悉,无法使其正常工作。我的原始示例允许用户选择特定的系列。因此位置必须是动态的,但是当我使用注释时,只能使它们显示在固定点。
这是我的图表的一个非常基本的示例:
library(highcharter)
#create dataframe
data <- data.frame(
type_1 = c("a", "a", "b", "b", "c", "c"),
type_2 = c("1", "2", "1", "2", "1", "2"),
n = c(5,8,10,4,7,9))
data
# create chart
highchart() %>%
hc_add_series(data, type = "bar", hcaes(x = type_1, group = type_2, y = n)) %>%
hc_plotOptions(series = list(stacking = 'normal')) %>%
hc_xAxis(categories = unique(data$type_1)
我想要的是a / b / c不出现在图例中,而是显示在栏旁边。
感谢您提供的任何帮助!
答案 0 :(得分:2)
您不需要使用注释。使用 dataLabels 更容易。它们默认放置在所需的位置,您可以使用 dataLabels.formatter 在其中显示任何内容。 当然,您现在可以禁用xAxis标签。
这是一个示例(我定义了一个数组 labels 并从中返回,但是您可以从 type_1 列表中返回值):
library(highcharter)
#create dataframe
data <- data.frame(
type_1 = c("a", "a", "b", "b", "c", "c"),
type_2 = c("1", "2", "1", "2", "1", "2"),
n = c(5,8,10,4,7,9))
data
# create chart
highchart() %>%
hc_add_series(data, type = "bar", hcaes(x = type_1, group = type_2, y = n), dataLabels = list(
enabled = TRUE,
formatter = JS(
"function() {
var labels = ['a', 'b', 'c'];
return labels[this.point.x];
}"
))) %>%
hc_xAxis(categories = data$type_1)
API参考:https://api.highcharts.com/highcharts/series.column.dataLabels
答案 1 :(得分:1)
这是使用注释的解决方案。
library(highcharter)
library(dplyr)
library(purrr)
data <- data.frame(
type_1 = c("a", "a", "b", "b", "c", "c"),
type_2 = c("1", "2", "1", "2", "1", "2"),
n = c(5,8,10,4,7,9) )
开始定义一列id
以唯一地标识每个条形。
(data$id <- mapply(function(x,y) paste0(x,y), data$type_1, data$type_2))
# [1] "a1" "a2" "b1" "b2" "c1" "c2"
然后将带有条形标签的列表添加到数据集中。
每个栏都由其id
引用。
data <- data %>%
mutate(labels = map(1:nrow(.), function(k) {
list(point=as.character(id[k]), text=as.character(n[k]),
backgroundColor="red", distance=5, style=list(fontSize="16px"))
})
)
# This is label for the first bar
data$labels[[1]]
# $point
# [1] "a1"
#
# $text
# [1] "5"
#
# $backgroundColor
# [1] "red"
#
# $distance
# [1] 5
#
# $style
# $style$fontSize
# [1] "16px"
最后,使用注释添加标签
highchart() %>%
hc_add_series(data, type = "bar", hcaes(x = "type_1", group = "type_2", y = "n")) %>%
hc_xAxis(categories = unique(data$type_1)) %>%
hc_annotations( list(labels=data$labels) )