Stacked Barchart with total amount of bars text
Nobody has claimed this yet.
- Dominant language
- R
- Stars
- 2.7k
- Forks
- 641
- PR merge metrics
- No merged PRs in 30d
Description
Problem: I have a stacked barchart. Above each of the stacked bars I want to have a total number (i.e. the sum of the two bars - here: total). I tried to take usage of add_text but it did not work out as expected. Any suggestions what to change?
Remark: I do not want to cast the data.table object. The target frame on which the visualizations shall be made is new_frame.
Many thanks
Brief description of the problem
library(data.table)
library(plotly)
Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.table(Animals, SF_Zoo, LA_Zoo)
new_frame <- data.table::melt(data, id.vars='Animals')
new_frame[, total := sum(value), by = Animals]
plot_ly(new_frame, x = ~Animals,
y = ~value,
type = 'bar',
name = ~variable,
text = ~paste(variable, value, total),
textposition = 'auto',
# insidetextfont = list(size = 10, color = 'black'),
hovertext = ~paste(
"<b>Hover text works IN/OUT</b><br>"),
hoverinfo = 'text',
hoverlabel = list(align = "left"),
showlegend = TRUE) %>%
add_text(
visible = "legendonly",
x= ~Animals,
y = ~total,
# showlegend = TRUE,
name = "Titel",
cliponaxis = FALSE,
textfont = list(size = 10)
)%>%
layout(yaxis = list(title = 'Count'), barmode = 'stack')

Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproducible R example using data.table::melt, plot_ly, and add_text, then inspect how stacked bar traces position the total labels. Done means displaying the sum above each stacked bar on new_frame without casting the data.table object.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- plotly, r
- Domain
- data-visualization
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100