2

I have the following dataset:

data <- structure(list(Q14 = c("< 5 people", "> 11 people", "6-10 people", 
NA), count = c(148L, 13L, 34L, 21L), var = c("Team Size", "Team Size", 
"Team Size", "Team Size")), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame"))

And I plot my geom_bar as follows:

library(ggplot2)
library(wesanderson)

ggplot(data) +
  geom_bar( aes(x = var, y = count, fill = Q14), stat = "identity", position = "fill") +
  coord_flip() + 
  theme(legend.position = "none", 
        axis.title.x=element_blank(), axis.title.y=element_blank()) +
  scale_fill_manual(values = wes_palette("Zissou1", 3, type = "continuous"))

I would like to print the labels inside the bar, as follows. Note: my editing skills suck, I'd like labels to be aligned of course, and they can be rotated CCW as well.

enter image description here

Another option is to obtain something as follows, which I also like:

enter image description here

Edward
  • 10,360
  • 2
  • 11
  • 26
Carrol
  • 1,225
  • 1
  • 16
  • 29

1 Answers1

2

One option is to use geom_text:

ggplot(data, aes(x = var, y = count, fill = Q14, label = Q14)) +
  geom_bar(stat = "identity", position = "fill", ) +
  geom_text(position = position_fill(vjust = 0.5), size = 3) +
  coord_flip() + 
  theme(legend.position = "none", 
        axis.title.x=element_blank(),
        axis.title.y=element_blank()) +
  scale_fill_manual(values = wes_palette("Zissou1", 3, type = "continuous"))

enter image description here

Another option is to use geom_label_repel from ggrepel:

library(ggrepel)
ggplot(data, aes(x = var, y = count, fill = Q14, label = Q14)) +
  geom_bar(stat = "identity", position = "fill", ) +
  geom_label_repel(position = position_fill(vjust = 0.5),
                   direction = "y",
                   point.padding = 1,
                   segment.size = 0.2, 
                   size = 3,
                   seed = 3) +
  coord_flip() + 
  theme(legend.position = "none", 
        axis.title.x=element_blank(),
        axis.title.y=element_blank()) +
  scale_fill_manual(values = wes_palette("Zissou1", 3, type = "continuous"))

enter image description here

Note that the seed parameter sets the random process of which direction each label goes. If you don't like the same one I do, pick a different number.

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
  • Second option is great, but the problem is the more categories I have (colours), and the thinner the bar gets, it really looks messy. – Carrol May 21 '20 at 00:08
  • 1
    Play with the other parameters of `geom_label_repel`, particularly `force = ` and `box.padding = ` or `direction = "both"`. – Ian Campbell May 21 '20 at 00:15