R:ggplot:使用dplyr与组平均值合并geom_points [英] R: ggplot: Combine geom_points using dplyr with group averages

查看:53
本文介绍了R:ggplot:使用dplyr与组平均值合并geom_points的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to add 2 different ggplots together using dplyr and 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中?

Another way to ask: how do I filter by 2 variable names and then add them together in same ggplot using dplyr and color variable points differently?

谢谢.

推荐答案

这是您想要的吗?

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程序包(v0.2.0)创建于2018-05-23.

Created on 2018-05-23 by the reprex package (v0.2.0).

这篇关于R:ggplot:使用dplyr与组平均值合并geom_points的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆