Reputation: 89
Good day. I have used ggplot
in R quite a lot. I have some basic knowledge missing about how to make pie charts in ggplot
. I want to make a pie chart for the variable puls$reykir
with percentages on the graph. The following code seems to draw a pie chart but the labeling is strange. How can I change the code in order to replace the strange labeling with a percentage in correct places instead? Here is my code:
puls <- read.table ("https://edbook.hi.is/gogn/pulsAll.csv", header=TRUE, sep=";")
ggplot(puls, aes(x = "", y = reykir, fill = reykir)) +
geom_bar(stat = "identity") +
coord_polar(theta = "y", start = 0, direction = 1)
Upvotes: 1
Views: 140
Reputation: 2727
You need to convert the table so you have a value column with the number of counts. Is this graph what you are looking for?
# convert to data.table
# install.packages("data.table") # for installing
library(data.table)
dt <- as.data.table(puls)
# .N getsthe count of the rows by reykir
dt2 <- dt[, .N, by=reykir]
# turn in to probability & view
dt2[, P := N/sum(N)]
dt2[]
# change y to P and add in the scale_y_continous for percent
ggplot(dt2, aes(x = "", y = P, fill = reykir)) +
geom_bar(stat = "identity") +
scale_y_continuous(labels = scales::percent) +
geom_text(aes(label=paste0(round(100*P, 1), "%")), position = position_stack(vjust=.5)) +
coord_polar(theta = "y", start = 0, direction = 1) +
theme_minimal()
Upvotes: 1