Reputation: 1169
I am trying to get the percentage on the y-axis. But some I could not manage to get it.
df <- tribble(
~id, ~min, ~max,
"1", 5, 40,
"2", 5, 50,
"3", 7, 70,
"4", 8, 90,
"5", 23, 100,
"6", 18, 40,
"7", 34, 50,
"8", 84, 150,
"9", 15, 70,
"10", 100, 90,
)
outs <- cut(df$min, breaks = c(0, 5, 10, 15, 20, 40, 60, 80, 100))
library(scales)
table(outs) %>%
as.data.frame() %>%
ggplot(aes(x = outs, y = Freq)) +
geom_col(col = "black", fill = "steelblue4", alpha = .4) +
geom_text(
aes(label = Freq, Freq = Freq + 0.05),
position = position_dodge(0.9),
vjust = -0.4) +
labs(x = "Min", y = "Number of ids") +
scale_y_continuous(labels = percent)
And this is the result:
I want to have it in both geom_text and the y-axis. Do you have any suggestions?
Upvotes: 0
Views: 250
Reputation: 16178
You have to first calculate the Freq by dividing over the sum of observations.
You can also modify your geom_text
to get label = paste0(Freq*100," %")
.
Finally, add some limits to the scale_y_continuous
to get a y-axis from 0 to 100%
outs = table(outs) / sum(table(outs))
outs %>%
as.data.frame() %>%
ggplot(aes(x = outs, y = Freq)) +
geom_col(col = "black", fill = "steelblue4", alpha = .4) +
geom_text(
aes(label = paste0(Freq*100," %"), Freq = Freq + 0.05),
position = position_dodge(0.9),
vjust = -0.4) +
labs(x = "Min", y = "Percentage of ids") +
scale_y_continuous(labels = percent, limits = c(0,1))
Does it answer your question ?
Upvotes: 1