R 使用管道操作符后分割的几何图形平滑
我遇到一个与ggplot2中的管道操作符相关的问题。我的数据集是“iris”,我的代码是:R 使用管道操作符后分割的几何图形平滑,r,plot,ggplot2,R,Plot,Ggplot2,我遇到一个与ggplot2中的管道操作符相关的问题。我的数据集是“iris”,我的代码是: iris %>% mutate(petalPlus = as.factor(ifelse(Petal.Length > 5.5, 1, 0))) %>% ggplot(aes(x = Petal.Length, y = Petal.Width, col = Species, shape = petalPlus)) + geom_point() + theme_bw() + geom
iris %>%
mutate(petalPlus = as.factor(ifelse(Petal.Length > 5.5, 1, 0))) %>%
ggplot(aes(x = Petal.Length, y = Petal.Width, col = Species, shape =
petalPlus)) +
geom_point() +
theme_bw() +
geom_smooth(method = "lm")
问题是我得到的是4条线性回归线(对于每种颜色和形状)。我想知道如何获得一条回归线,以及我目前获得4条回归线的原因是什么。之所以获得4条回归线,是因为
geom_smooth
从ggplot
调用继承了shape
和col
aes
,它们隐式定义了组
要避免这种情况,请在每个geom中定义aes
,或仅在geom\u smooth
中定义aes,禁用继承:
库(dplyr)
图书馆(GG2)
虹膜%>%
变异(花瓣长度=as.factor(如果其他(花瓣长度>5.5,1,0)))%>%
ggplot()+
几何点(aes(x=花瓣长度,
y=花瓣宽度,
col=物种,
形状=花瓣状)+
主题_bw()+
几何平滑(aes(x=花瓣长度,y=花瓣宽度),方法=“lm”)
iris%>%
变异(花瓣长度=as.factor(如果其他(花瓣长度>5.5,1,0)))%>%
ggplot(aes(x=花瓣长度,
y=花瓣宽度,
col=物种,
形状=petalPlus))+
几何点()+
主题_bw()+
geom_smooth(aes(x=Petal.Length,y=Petal.Width),method=“lm”,inherit.aes=FALSE)
由(v0.2.0)于2018-05-23创建。您将获得4行,因为geom_smooth
继承了形状
和col
aes
调用中的aes
,并隐式定义了组
要避免这种情况,请在每个geom中定义aes
,或仅在geom\u smooth
中定义aes,禁用继承:
库(dplyr)
图书馆(GG2)
虹膜%>%
变异(花瓣长度=as.factor(如果其他(花瓣长度>5.5,1,0)))%>%
ggplot()+
几何点(aes(x=花瓣长度,
y=花瓣宽度,
col=物种,
形状=花瓣状)+
主题_bw()+
几何平滑(aes(x=花瓣长度,y=花瓣宽度),方法=“lm”)
iris%>%
变异(花瓣长度=as.factor(如果其他(花瓣长度>5.5,1,0)))%>%
ggplot(aes(x=花瓣长度,
y=花瓣宽度,
col=物种,
形状=petalPlus))+
几何点()+
主题_bw()+
geom_smooth(aes(x=Petal.Length,y=Petal.Width),method=“lm”,inherit.aes=FALSE)
由(v0.2.0)于2018年5月23日创建。这不是因为您使用了管道操作员,而是因为您将所有的aes
规范放在一起。这意味着geom_smooth
函数需要所有颜色和形状组合的不同线条。一种方法是颠倒geom调用的顺序,并根据您的规范定制它们各自的aes
:
png()
print(
iris %>%
mutate(petalPlus = as.factor(ifelse(Petal.Length > 5.5, 1, 0))) %>%
ggplot(aes(x = Petal.Length, y = Petal.Width)) +
theme_bw() +
geom_smooth(method = "lm")+
geom_point(aes(col=Species,shape=petalPlus))
dev.off() )
这不是因为您使用了管道操作器,而是因为您将所有的aes
规范放在一起。这意味着geom_smooth
函数需要所有颜色和形状组合的不同线条。一种方法是颠倒geom调用的顺序,并根据您的规范定制它们各自的aes
:
png()
print(
iris %>%
mutate(petalPlus = as.factor(ifelse(Petal.Length > 5.5, 1, 0))) %>%
ggplot(aes(x = Petal.Length, y = Petal.Width)) +
theme_bw() +
geom_smooth(method = "lm")+
geom_point(aes(col=Species,shape=petalPlus))
dev.off() )
尝试从aes
中取出/取出col=Species
和shape=petalPlus
并查看会发生什么情况尝试从aes
中取出/取出col=Species
和shape=petalPlus
并查看可能发生的重复情况