John Smith
John Smith

Reputation: 2886

R ggplot2: Adding another geom to coord_polar

I have a plot i wish to add another layer to Th plot is below. I want to overlay another polar plot on it to see that the numbers "match up"

In the example below I have create the plot for one species of the iris dataset. I would like to overlay another plot of a different species

Thank you for your time

library(ggplot2)
library(dplyr)

mydf <- iris
plot.data <- tidyr::gather(mydf,key = attribute ,value = avg_score, Sepal.Length:Petal.Width)


plot.data <- plot.data %>% 
   filter(Species == 'setosa') %>% 
   group_by(attribute) %>% 
   summarise(attr_mean = mean(avg_score))

ggplot(plot.data, aes(x=attribute, y = attr_mean, col = attribute)) +
   geom_bar(stat = "identity", fill = 'white') +
  coord_polar(theta = "x") +
  theme_bw() 

Upvotes: 0

Views: 509

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70643

This is quite the pedestrian way of doing things.

plot.setosa <- plot.data %>% 
  filter(Species == 'setosa') %>% 
  group_by(attribute) %>% 
  summarise(attr_mean = mean(avg_score))

plot.virginica <- plot.data %>% 
  filter(Species == 'virginica') %>% 
  group_by(attribute) %>% 
  summarise(attr_mean = mean(avg_score))

ggplot(plot.setosa, aes(x=attribute, y = attr_mean, col = attribute)) +
  geom_bar(stat = "identity", fill = 'blue', alpha = 0.25) +
  geom_bar(data = plot.virginica, stat = "identity", fill= "green", alpha = 0.25,
           aes(x = attribute, y = attr_mean, col = attribute)) + 
  coord_polar(theta = "x") +
  theme_bw()

enter image description here

And a slightly less pedestrian.

xy <- plot.data %>%
  group_by(Species, attribute) %>%
  summarise(attr_mean = mean(avg_score))

ggplot(xy, aes(x = attribute, y = attr_mean, color = attribute, fill = Species)) +
  theme_bw() +
  geom_bar(stat = "identity", alpha = 0.25) +
  coord_polar(theta = "x")

enter image description here

Upvotes: 3

Related Questions