I would like to create a plot with R and Highcharter and place an annotation on it that is connected to two points (and not just one point).
That ist what I try:
# Laden der Bibliothek
library(highcharter)
# Laden der Titanic-Daten aus dem 'datasets'-Paket
data <- datasets::Titanic
# Umstrukturierung der Daten für den Plot
data_long <- as.data.frame(as.table(data))
colnames(data_long) <- c("Class", "Sex", "Age", "Survived", "Count")
data_long$Count <- as.numeric(data_long$Count)
# Filtern der Daten für Erwachsene
data_long <- subset(data_long, Age == "Adult")
# Erstellen des gestapelten Balkendiagramms
hchart(data_long, "column", hcaes(x = Sex, y = Count, group = interaction(Survived, Class)), stack = TRUE) %>%
hc_plotOptions(column = list(stacking = "percent"))%>%
hc_annotations(list(
labels = list(
list(
point = list(x = 0.5, y = 60, xAxis = 0, yAxis = 0), # Zwischen den Bars
text = "Differenz: 12%",
style = list(fontSize = "11px") # Optional: Anpassen der Schriftgröße
)
)
))
The result:
The expected result: expected result
This is one (hacky) option which use shape="connector"
to draw the connecting lines and using allowOverlap=TRUE
connects to the second point using a transparent label:
library(highcharter)
# Erstellen des gestapelten Balkendiagramms
hchart(data_long, "column", hcaes(
x = Sex, y = Count,
group = interaction(Survived, Class)
), stack = TRUE) %>%
hc_plotOptions(column = list(stacking = "percent")) |>
hc_annotations(
list(
labelOptions = list(
shape = "connector",
allowOverlap = TRUE
),
labels = list(
list(
point = list(
x = 1,
y = 35,
xAxis = 0, yAxis = 0
),
text = "Differenz: 12%",
style = list(fontSize = "11px"),
x = -130,
y = -120
),
list(
point = list(
x = 0,
y = 65,
xAxis = 0, yAxis = 0
),
text = "Differenz: 12%",
style = list(fontSize = "11px", color = "transparent"),
x = 130,
y = -15
)
)
)
)