问题
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")
Graph 1
ggplot(data = diamonds, mapping = aes(x = cut, y=..prop.., fill = cut)) +
geom_bar(width = 1) + coord_polar(theta = "x")
Graph 2
ggplot(data = diamonds, mapping = aes(x = cut, fill = cut)) +
geom_bar()
Graph 3
回答1:
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.
回答2:
How about this?
ggplot(diamonds, aes(x = "", fill = cut)) +
geom_bar() +
coord_polar(theta = "y")
It yields:
https://imgur.com/a/leSmIPT
来源:https://stackoverflow.com/questions/47238098/plotting-pie-charts-in-ggplot2