I want to plot a proper pie chart. However, most of the previous questions on this site were drawn from stat = identity
. How can I plot a normal pie chart like graph 2 with the angle proportional to proportion of cut
? I am using the diamonds
data frame from ggplot2.
ggplot(data = diamonds, mapping = aes(x = cut, fill = cut)) +
geom_bar(width = 1) + coord_polar(theta = "x")
ggplot(data = diamonds, mapping = aes(x = cut, y=..prop.., fill = cut)) +
geom_bar(width = 1) + coord_polar(theta = "x")
ggplot(data = diamonds, mapping = aes(x = cut, fill = cut)) +
geom_bar()
We can first calculate the percentage of each cut
group. I used the dplyr
package for this task.
library(ggplot2)
library(dplyr)
# Calculate the percentage of each group
diamonds_summary <- diamonds %>%
group_by(cut) %>%
summarise(Percent = n()/nrow(.) * 100)
After that, we can plot the pie chart. scale_y_continuous(breaks = round(cumsum(rev(diamonds_summary$Percent)), 1))
is to set the axis label based on cumulative percentage.
ggplot(data = diamonds_summary, mapping = aes(x = "", y = Percent, fill = cut)) +
geom_bar(width = 1, stat = "identity") +
scale_y_continuous(breaks = round(cumsum(rev(diamonds_summary$Percent)), 1)) +
coord_polar("y", start = 0)
Here is the result.