I need to put all the labels "inside" the bars of my ggplot. I having problems because I need to group the variables and then include the labels inside the bars.
This is my code:
df <- structure(list(name = c("Player 1", "Player 2", "Player 3",
"Player 4", "Player 5", "Player 6", "Player 7", "Player 8",
"Player 9", "Player 10", "Player 11", "Player 12", "Player 13"
), pos = c("Lateral", "Lateral", "Central", "Central",
"Meio Campo", "Extremo", "Extremo", "Meio Campo", "Avancado",
"Meio Campo", "Avancado", "Meio Campo", "Lateral"), total = c(9263L,
10451L, 9845L, 9719L, 11650L, 10831L, 11143L, 8816L, 7666L, 9587L,
2703L, 2085L, 1282L)), row.names = c(NA, -13L), class = c("tbl_df",
"tbl", "data.frame"))
This is what I tried so far:
df %>% mutate(name = fct_reorder(name,total)) %>% ggplot(aes(pos, total,fill = pos, group = total,label = name))
geom_col(show.legend = FALSE,
position = position_dodge2(),width = .5)
geom_label(aes(group = name),color = "white",
position = position_dodge2(width = .9),
show.legend = FALSE) coord_flip()
CodePudding user response:
An option would be using geom_text
and displaying the labels inside your bars. You can use the following code:
library(tidyverse)
df %>% mutate(name = fct_reorder(name,total)) %>% ggplot(aes(pos, total,fill = pos, group = total,label = name))
geom_col(show.legend = FALSE,
position = position_dodge2(),width = .5)
geom_text(aes(group = name),color = "white",
position = position_dodge2(width = 0.5),
show.legend = FALSE, hjust = 1.2, size = 2) coord_flip()
Output:
CodePudding user response:
To move your labels inside the bars set the width for the dodging of the labels the same as the width of your bars and use hjust=1
to align the labels to the right. Additionally with small bars I would suggest to reduce the font size and as a matter of taste remove the outline of the labels:
library(ggplot2)
library(dplyr)
library(forcats)
df %>%
mutate(NOME = fct_reorder(NOME, TOTAL.DISTANCE)) %>%
ggplot(aes(PLAYER.POSITION, TOTAL.DISTANCE, fill = PLAYER.POSITION, label = NOME))
geom_col(aes(group = NOME),
show.legend = FALSE,
position = position_dodge2(), width = .5
)
geom_label(aes(group = NOME),
color = "white", hjust = 1, label.size = 0,
position = position_dodge2(width = .5),
show.legend = FALSE, size = 8 / .pt, label.padding = unit(2, "pt")
)
coord_flip()