Limited understanding of pie charts in ggplot

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

Answers (1)

Jonny Phelps
Jonny Phelps

Reputation: 2727

http://www.sthda.com/english/wiki/ggplot2-pie-chart-quick-start-guide-r-software-and-data-visualization

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()

enter image description here

Upvotes: 1

Related Questions