0

I have created a stacked bar chart with segment total labels and column/bar total labels. Segment total labels are placed in the middle of each segment, column total labels are placed on top of each column/bar.

ggplot(dataset, aes(x = Company, y = Incidents, fill = IncidentLevel)) +
  geom_col(position = position_stack(reverse = TRUE)) +
  # segment totals
  geom_text(data = subset(dataset, Incidents > 10),
        aes(label = Incidents), size = 4, position = position_stack(reverse = TRUE, vjust = 0.5)) +
  # column totals
  stat_summary(fun.y = sum, aes(label = ..y.. , group = Company), geom = "text", vjust = -1)

The problem is that the tallest bar label is cut by the end of the graph. How to readjust the y axis in order to fully include the tallest label?

I was thinking about two possible solutions, although I don't know where to start with any of them:

  1. use coord_cartesian to fix the y axis limits so that it's c(0, y-range + tallest bar label height). Then the problem is how to get the y range? How to get the label height?
  2. increase the y range proportionally: y-range = y-range * 1.01- Then the problem is only: how to get the y-range?

P.S. : sorry, can't share the dataset. The question though is valid regardless the actual plot. Whenever you add a label through stat_summary or similar function, the axes don't readjust to it.

Pigna
  • 2,792
  • 5
  • 29
  • 51
  • 2
    When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. You don't have to share your actual data, just something that reproduces the problem. Feel free to use a built in dataset. – MrFlick Feb 16 '18 at 16:41
  • Possible duplicate of [How to make geom\_text plot within the canvas's bounds](https://stackoverflow.com/questions/17241182/how-to-make-geom-text-plot-within-the-canvass-bounds) – dww Feb 16 '18 at 20:15

0 Answers0