I have a horizontal geom_col
bar with position = "fill"
. I want to label the bar with the same color as the fill aesthetic, but doing so caused the text colors to overlap with the fill.
library(tidyverse)
library(cowplot)
library(ggrepel)
diamonds %>%
count(cut, color) %>%
filter(cut == "Fair") %>%
mutate(lab = paste0(color, " (n = ", n, ")"),
color = fct_reorder(color, n)) %>%
ggplot(aes(cut, n , fill = color, label = lab)) +
geom_col(position = "fill") +
geom_text_repel(aes(color = color), position = "fill", direction = "x") +
coord_flip() +
theme_cowplot()
Therefore I would like to repel the labels vertically with geom_text_repel
. However, when I do that, it shows an error:
... +
geom_text_repel(aes(color = color), position = "fill", direction = "x", nudge_y = 1) +
...
Error: Specify either
position
ornudge_x
/nudge_y
How can I correctly repel text labels vertically with position = "fill"
? The labels should look similar to the following:
One way could be to use ggpp::position_fillnudge
. Adjust x = 0.7
for the vertical distance of the labels.
library(tidyverse)
library(cowplot)
library(ggrepel)
diamonds %>%
count(cut, color) %>%
filter(cut == "Fair") %>%
mutate(lab = paste0(color, " (n = ", n, ")"),
color = fct_reorder(color, n)) %>%
ggplot(aes(cut, n , fill = color, label = lab)) +
geom_col(position = "fill") +
coord_flip() +
theme_cowplot() +
geom_text_repel(aes(color = color), position = ggpp::position_fillnudge(vjust = 0.5, x = 0.7))