R:ggplot:使用dplyr将geom_points与组平均值相结合

时间:2018-05-23 18:16:34

标签: r ggplot2 dplyr

我想使用dplyr和ggplot将2个不同的ggplot加在一起:

iris_setosa<- iris %>% filter( Species == "setosa")%>%
           do(plots=ggplot(data=.) +
           aes(x=Petal.Width, y=Petal.Length) + geom_point() 



iris_virginica<- iris %>% filter( Species == "virginica")%>%
           do(plots=ggplot(data=.) +
           aes(x=Petal.Width, y=Petal.Length) + geom_point() 

另一种问题:如何使用2个变量名进行过滤,然后使用dplyr和颜色变量点以不同的方式将它们添加到同一个ggplot中?

谢谢。

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

library(tidyverse)        

theme_set(theme_bw())

# Mean per Species
plt1 <- iris %>% 
  filter(Species %in% c("setosa", "virginica")) %>% 
  group_by(Species) %>% 
  mutate(mean_length = mean(Petal.Length, na.rm = TRUE),
         mean_width  = mean(Petal.Width,  na.rm = TRUE)) %>% 
  ungroup() %>% 
  ggplot(., aes(x=Petal.Width, y=Petal.Length, color=Species)) + 
  geom_point() +
  facet_grid(~ Species, scales = "free_x") +
  geom_hline(aes(yintercept = mean_length, linetype = c("Mean length"))) +
  geom_vline(aes(xintercept = mean_width,  linetype = c("Mean width")), 
             show.legend = FALSE) 

plt1 + scale_linetype_manual(NULL, 
                              values = c(5, 3),
                              labels = c("Mean length", "Mean width")) +
  guides(color = guide_legend(order = 1)) +
  # Move legends closer to each other 
  theme(
        legend.spacing.y = unit(0.05, "cm"),
        legend.margin = margin(0, 0, 0, 0),
        legend.box.margin = margin(0, 0, 0, 0))

# Mean for all Species
plt2 <- iris %>% 
  filter(Species %in% c("setosa", "virginica")) %>% 
  mutate(mean_length = mean(Petal.Length, na.rm = TRUE),
         mean_width  = mean(Petal.Width,  na.rm = TRUE)) %>% 
  ggplot(., aes(x=Petal.Width, y=Petal.Length, color=Species)) + 
  geom_point() +
  geom_hline(aes(yintercept = mean_length, linetype = c("Mean length"))) +
  geom_vline(aes(xintercept = mean_width,  linetype = c("Mean width")), 
             show.legend = FALSE) 

plt2 + scale_linetype_manual(NULL, 
                             values = c(1, 4),
                             labels = c("Mean length (all)", "Mean width (all)")) +
  guides(color = guide_legend(order = 1)) +
  theme(
    legend.spacing.y = unit(0.05, "cm"),
    legend.margin = margin(0, 0, 0, 0),
    legend.box.margin = margin(0, 0, 0, 0))

reprex package(v0.2.0)创建于2018-05-23。