如何用R语言Highcharter实现堆叠点图(附ggplot参考代码)
用highcharter实现ggplot堆叠点图的方法指引
问题说明
我通过ggplot代码生成了堆叠点图:
ggplot(dt, aes(x = 1, y = yearValueDecimal)) + geom_dotplot(binaxis='y', stackdir='up', stackratio=2, dotsize=0.5) + coord_flip()
尝试用highcharter实现同类图表时,当前代码无法达到预期效果:
dt %>% hchart(type = 'scatter', hcaes(x = 1, y = 'yearValueDecimal')) %>% hc_plotOptions(stacking = "normal")
数据准备
数据生成代码:
sample(2016:2023,40,replace = TRUE,prob = NULL) -> yearValue sample(1:12,40,replace = TRUE,prob = NULL) -> monthValue sample(1:28,40,replace = TRUE,prob = NULL) -> dayValue ((dayValue-1)/30) + ((monthValue-1)/12)+(yearValue) -> yearValueDecimal
数据结构示例:
structure(list(yearValueDecimal = c(2022.21666666667, 2022.83333333333, 2016.98333333333, 2021.43333333333, 2023.7, 2022.03333333333, 2022.86666666667, 2022.46666666667, 2020.81666666667, 2020.1, 2022.31666666667, 2023.93333333333, 2016.48333333333, 2016.83333333333, 2018.81666666667, 2017.4, 2019.5, 2017.43333333333, 2019.58333333333, 2019.7, 2022.3, 2020.25, 2023.41666666667, 2019.35, 2019.11666666667, 2017.73333333333, 2019.78333333333, 2019.33333333333, 2022.86666666667, 2020.25, 2021.26666666667, 2016.56666666667, 2016.53333333333, 2023.83333333333, 2022.56666666667, 2021.85, 2018.3, 2022.66666666667, 2019.68333333333, 2019.95)), row.names = c(NA, -40L), class = c("data.table", "data.frame"))
实现方案
Highcharts没有原生的堆叠散点图配置,需要通过预计算点的x轴偏移量模拟堆叠效果,具体代码如下:
library(data.table) library(highcharter) # 转换为data.table便于分组计算 setDT(dt) # 按y值分组,计算每个点在组内的序号,生成堆叠偏移量 dt[, point_idx := seq_len(.N), by = yearValueDecimal] # 控制堆叠宽度,可根据需求调整 stack_width <- 0.8 dt[, x_offset := 1 + (point_idx - (.N + 1)/2) * stack_width / .N] # 绘制堆叠点图 dt %>% hchart(type = "scatter", hcaes(x = x_offset, y = yearValueDecimal)) %>% # 配置x轴,隐藏多余刻度和标签 hc_xAxis( title = list(text = ""), tickPositions = c(1), labels = list(enabled = FALSE) ) %>% # 调整点大小,对应ggplot的dotsize hc_plotOptions( scatter = list( marker = list(radius = 3) ) ) %>% # 翻转坐标轴,对应ggplot的coord_flip() hc_chart(inverted = TRUE)
关键说明
- 偏移量计算:通过
point_idx为每个同y值的点分配位置,让堆叠点以x=1为中心对称分布,避免重叠 - 参数调整:修改
stack_width可控制堆叠的整体宽度,调整marker.radius能改变点的大小 - 坐标轴翻转:
hc_chart(inverted = TRUE)实现和coord_flip()一致的效果
内容的提问来源于stack exchange,提问作者notjackwyp
相关产品推荐
相关产品推荐

