I am trying to make a pie chart with percentages. In order to do that I wrote this lines of codes
library(ggplot2)
df <- data.frame(
group = c("Male", "Female"),
value = c(15000, 10000))
head(df)
p <- ggplot(df, aes(x="", y = value, fill=group))
geom_bar(width = 1, stat = "identity") coord_polar("y", start=0)
require(scales)
p scale_fill_brewer("Blues") blank_theme
geom_text(aes(y = value/2 c(0, cumsum(value)[-length(value)]),
label = percent(value/100)), size=5)
But unfortunately these lines of code don’t give me percentage numbers. So can anybody help me how to solve this problem and get real percentages of 60% for male and 40% for female.
CodePudding user response:
Use just sum
to count both genders. Example: percent(1000 / sum(df$value))
will return "4%"
.
library(tidyverse)
library(scales)
#>
#> Attaching package: 'scales'
#> The following object is masked from 'package:purrr':
#>
#> discard
#> The following object is masked from 'package:readr':
#>
#> col_factor
df <- data.frame(
group = c("Male", "Female"),
value = c(15000, 10000)
)
df
#> group value
#> 1 Male 15000
#> 2 Female 10000
ggplot(df, aes(x = "", y = value, fill = group))
geom_bar(width = 1, stat = "identity")
coord_polar("y", start = 0)
scale_fill_brewer("Blues")
theme_void()
geom_text(aes(
y = value / 2 c(0, cumsum(value)[-length(value)]),
label = percent(value / sum(value))
), size = 5)
Created on 2021-09-22 by the reprex package (v2.0.1)