# Pie chart with percentage for different groups

Hi

I want to do a pie chart. I have a table with column of age (pup, juvenile and adult) and another with harbours (Chichester and Langstone). Is it possible to do a pie chart for every harbour how is the place preference by age groups in percentage? Like pie chart Chicester harbour and there like 45% of juvenile and 15% of pups and 40% of adult.

Short answer: yes; consider the code below

Long answer: can you provide a REPRoducible EXample with your data structure? It would allow for a more specific answer...

PS: zdravíme Čechy!

``````library(ggplot2)

ggplot(mtcars, aes(x = "", fill = as.factor(cyl))) +
geom_bar(position = "fill", width = 1) +
coord_polar(theta = "y") +
facet_grid(cols = vars(vs))
``````

r_seals.pdf (67.5 KB)
Here is whole the data set. I am not sure how to use the formula. Please, can you specify where I can put what? I am sorry I am just a beginner.
Take zdravim Oki, in that case the code should be something like:

``````library(ggplot2)

ggplot(data = r_seals, aes(x = "", fill = as.factor(Cohort))) +
geom_bar(position = "fill", width = 1) +
coord_polar(theta = "y") +
facet_grid(cols = vars(Haulout))
``````

assuming your source data frame is called `r_seals`.

That is almost perfect. Is it possible to put there exact percentages?

r_cohort_haulout.pdf (13.2 KB)

It is technically possible to calculate the percentages in ggplot call, but it will not be very clear (nor beginner friendly).

I suggest you pre-calculate the summarisation first (i.e. outside of the ggplot) and then just add it via `geom_text()` with `position = position_fill(vjust = 0.5)` so that it is shown in the middle of the pie wedges.

Thank you so much And one more question, is it possible to make histogram only for Harbour seals and their scars from human?

Surely it is; consider something along the lines of this code (I am using only the first 4 rows of your seals dataset, as copying from pdf is a chore):

``````library(tidyverse)

seals <- data.frame(species = c("Harbour", "Harbour", "Harbour", "Harbour"),
ScarHuman = c(2, 2, 2, 3))

seals <- seals %>%
filter(species == "Harbour")

ggplot(seals, aes(x = ScarHuman)) +
geom_bar(fill = "firebrick") # the fill color is just for the looks
``````

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.