Reputation: 11
I have this df
species<-c("Platanus acerifolia Willd.","Platanus acerifolia Willd.","Platanus occidentalis L.",
"Morus alba L.","Platanus occidentalis L.","Celtis australis L.")
kategorija<-c(3,2,1,2,3,3)
df<-data.frame(species,kategorija)
and I need to make a pie chart from the frequencies of the categories labelled with their percentages.
Upvotes: 1
Views: 245
Reputation: 5620
You could also make the pie plot using dplyr
and ggplot
. It requires a little more of coding, but the result might be more satisfactory.
library(ggplot2)
library(dplyr)
#Use dplyr to get percentages per kategorija
df_plot<-df %>%
count(kategorija) %>%
mutate(percent = round((100 * n / sum(n)),2))
#Create the bar plot
p2 <- ggplot(df_plot, aes(x = "", y = percent, fill = factor(kategorija)))+
geom_bar(width = 1, stat = "identity") +
#Transform the bar plot to pie plot
coord_polar("y", start = 0) +
#Add labels to each part of the pie and add some theme adjustments
geom_text(aes(y = cumsum(rev(percent)) - rev(percent)/2,
label = paste(rev(percent),"%")), size=4) +
# Add label for legend
labs(fill = "Kategorija")+
theme_minimal() +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text = element_blank(),
panel.border = element_blank(),
panel.grid=element_blank(),
axis.ticks = element_blank())
This code created the following plot:
Upvotes: 1
Reputation: 4879
Here is an easy way to do this using ggstatsplot
:
library(ggstatsplot)
species <- c(
"Platanus acerifolia Willd.", "Platanus acerifolia Willd.", "Platanus occidentalis L.",
"Morus alba L.", "Platanus occidentalis L.", "Celtis australis L."
)
kategorija <- c(3, 2, 1, 2, 3, 3)
df <- data.frame(species, kategorija)
ggpiestats(df, species, counts = kategorija, results.subtitle = FALSE)
Created on 2021-02-22 by the reprex package (v1.0.0)
Upvotes: 1
Reputation: 13372
You can try
pie(table(df$kategorija), labels = paste(round(prop.table(table(df$kategorija))*100), "%", sep = ""), col=rainbow(nrow(df)))
legend('topright', legend = paste('category', table(df$kategorija)), fill=rainbow(nrow(df)))
Upvotes: 1