将geom_smooth添加到箱线图 [英] Add geom_smooth to boxplot

查看:165
本文介绍了将geom_smooth添加到箱线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向一些箱形图添加geom_smooth()趋势,但是无法正确获取图层.

I'm trying to add a geom_smooth() trend to some a boxplot graph, but am not getting the layers correctly.

如何将这两个合并在一起?

How can I merge these two together?

geom_boxplot:

ggplot(test) + geom_boxplot(aes(x=factor(year), y = dm))

geom_smooth

ggplot(test, aes(year, dm)) + geom_smooth() 

geom_boxplot和geom_smooth

ggplot(test) + geom_boxplot(aes(x=factor(year), y = dm)) + geom_smooth(aes(x = year, y = dm))

推荐答案

我使用了mtcars公共数据,因为询问者没有使用它.

I used the mtcars public data as it did not have the use by the asker.

data(mtcars)

像往常一样创建箱线图,并分配给对象.我将随机变量作为箱形图的一个因素,并将另一个变量作为数字.

Create the boxplot, as usual, and assign to object. I took a random variable as a factor for the boxplot and another variable as numeric.

g <- ggplot(mtcars, aes(factor(carb), mpg)) + geom_boxplot()

添加geom_smooth. geom_smooth从geom_boxplot继承了必要的信息.

Add the geom_smooth. The geom_smooth inherits the necessary information from the geom_boxplot.

g + geom_smooth(method = "lm", se=TRUE, aes(group=1))

请注意,在这种情况下,geom_smooth需要使用表达式aes(group=1).如果没有它,R将返回错误:

Noted that the expression aes(group=1) it's required by the geom_smooth in this case. Without it, R returns the error:

geom_smooth:每个组只有一个唯一的x值.也许您想要aes(group = 1)?

用于固定线平滑度的值是线性回归的系数,而截距对应于系数的最低水平(carb = 1)

The values for fixing the line smoothing are the coefficients of the linear regression, whereas the intercept corresponds to the lowest level of the factor (carb = 1)

这篇关于将geom_smooth添加到箱线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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