I have a vector of values that I would like to display as a pie chart. The vector consists of 1's, 2's, and 3's, and I would like my pie chart to display the percentage of 1's, 2's, and 3's in the vector in addition to labels for the areas. The 1's would be Democrats, 2's Republicans, and 3's Independents. The vector that I have been working with is a column of a dataframe. There may be some type issues, although I've passed it using as.numeric() and as.factor().
Here is an example of the df (note, as you can see in the code, I'm intersted in col Q7):
Q6 Q7 Q8 Q9
3 30 3 5 1
4 30 3 5 1
5 65 3 2 2
6 29 3 5 1
7 23 1 4 1
8 24 1 5 1
Here is the code that I have been trying:
install.packages('ggplot2')
library(ggplot2)
# pie graph for party
pie <- ggplot(data=data, aes(x = as.factor(data$Q7), fill = factor(cyl)))
pie + coord_polar(theta = "y")
It returns an error: 'No layers in plot'
Thanks for the help!
Polar charts in ggplot are basically transformed stacked bar charts so you need geom_bar
to make it work. We'll use a single group (x = factor(1)
) to bring all values together and fill
on the column of interest to divide the area. At this point you'll get a bar chart with a single bar.
bar <- ggplot(data, aes(x = factor(1), fill = factor(Q7))) + geom_bar(width = 1)
bar
All what is left is to add coord_polar
:
pie <- bar + coord_polar(theta = "y")
pie
You can add theme_void()
to drop axes and labels:
pie + coord_polar(theta = "y") + theme_void()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With