Reputation: 535
I have issues having the percentage information at the right locations on my pie chart. Could someone very kindly help me on that? Thank you very much!
#sample dataframe
d <- data.frame(facet=c('a','b','c', "d"), value=c('0.46','0.11','0.18', "0.25"))
d$value <- as.numeric(as.character(d$value))
blank_theme <- theme_minimal()+
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.border = element_blank(),
panel.grid=element_blank(),
axis.ticks = element_blank(),
plot.title=element_text(size=14, face="bold")
)
d$perc <- round(d$value/sum(d$value) * 100,0)
d$pos <- cumsum(d$perc) - sapply(d$perc,function(x) cumsum(x)-0.5*x)
bp <- ggplot(data=d, aes(x="", y=perc, fill=facet))+
geom_bar(width = 1, stat = "identity") +
geom_text(aes(x="", y=pos, label=paste0(perc,"%"))) +
#geom_text(aes(x="", y=value/4+ c(0, cumsum(value)[-length(value)]), label=percent(value/100)))
scale_fill_manual(values = c("a" = "#b2df8a", "b" = "#238b45", "c" = "#636363", "d"="orange"))
bp
pie <- bp + coord_polar("y", start=0) + blank_theme +
theme(axis.text.x=element_blank())
pie
Upvotes: 3
Views: 377
Reputation: 48191
It happens that for some reason ggplot2
goes to the other direction when dealing with labels. Hence, instead using
d$pos <- 100 - (cumsum(d$perc) - sapply(d$perc, function(x) cumsum(x) - 0.5 * x))
gives
Upvotes: 1
Reputation: 4879
This is straightforward to achieve with ggpiestats
function. It only requires slight modification to your dataframe-
library(ggstatsplot)
set.seed(123)
# data
d <-
data.frame(
facet = c('a', 'b', 'c', "d"),
value = c(46, 11, 18, 25)
)
# plot with statistical details in the subtitle
ggstatsplot::ggpiestats(data = d,
main = facet,
counts = value)
In case you don't want statistical test details and want to further customize aesthetics of the plot, you can also use ggplot2
functions-
# customizing it further
# change the slice label
ggstatsplot::ggpiestats(data = d,
main = facet,
counts = value,
slice.label = "both",
package = "wesanderson",
palette = "Royal2") +
ggplot2::labs(subtitle = NULL)
Created on 2019-02-09 by the reprex package (v0.2.1)
Upvotes: 1