Hello,
First, sample data.
set.seed(2021)
year <- rep(2016:2019, 2)
percentage <- runif(length(year), 0.25, 0.70)
gender <- rep(c("M", "F"), each = 4)
graph_text <- data.frame(year, percentage, gender)
1) You have expand = c(0,0). Like this there is no space above the
greatest bar. In order to make room, change to limits = c(0, ymax + 10
percent).
2) Make the width of the bars larger, position_dodge(width = 0.9)
3) Assign a aesthetic color in geom_text, if you want the bars and text
colors to be the same, assign a value outside aes() if you want only one
color for the text. See at the end.
4) Not asked but I use scales::percent to make the percentages
automatic. Change back to your code if not needed.
ymax <- max(graph_text$percentage)
ggplot(aes(x=year, y=percentage, group=gender, fill=gender), data =
graph_text)+
geom_bar(position = 'dodge', stat='identity')+
geom_text(
aes(label = scales::percent(percentage, accuracy = 0.1), color =
gender),
position = position_dodge(width = 0.9),
size = 5,
vjust = 0
)+
scale_y_continuous(
limits = c(0, 1.1*ymax),
labels = scales::percent
)+
theme_classic()
The following geom_text will change the text labels color to red.
geom_text(
aes(label = scales::percent(percentage, accuracy = 0.1)),
position = position_dodge(width = 0.9),
#
color = "red",
#
size = 5,
vjust = 0
)
Hope this helps,
Rui Barradas
Às 17:52 de 19/08/21, bharat rawlley via R-help escreveu:
Hello
I have tried to create the following graph using ggplot2 using the following
code -
ggplot(aes(x=year, y=percentage, group=gender, fill=gender), data =
graph_text)+ geom_bar(position = 'dodge', stat='identity')+
scale_y_continuous(expand = c(0,0))+ theme_classic()+ geom_text(aes(label =
percentage), size = 5, position = position_dodge(width = 0.5), vjust=0)
I wanted to ask
1) In the last plot why is the label on top not showing up even when I save the
image as a pdf?
2) Is there anyway to make the labels appear in the middle of the bar? It is
aligned to the left right now
3) Is there any way to change the colour of the labels on the top of the bars?
Thank you!
______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.