我制作了一个散点图并在上面画了一条线;现在我需要更改 x 轴的刻度级别标签,它是连续的。数据:
y <- data.frame(a = 1:5, b = 5:9)
> y
a b
1 1 5
2 2 6
3 3 7
4 4 8
5 5 9
我绘制它:
ggplot(y, aes(a, b))+
geom_jitter()+
stat_summary(fun.data = mean_cl_normal)+
geom_smooth(method = 'lm', formula = y~x)
这还不错,但我需要更改 x 轴刻度级别的标签,以使它们有意义,所以我尝试这样做:
ggplot(y, aes(a, b))+
geom_jitter()+
stat_summary(fun.data = mean_cl_normal)+
geom_smooth(method = 'lm', formula = y~x)+
scale_x_discrete("A_Variable", c("a","b","c","d","f"))
这不起作用。我从另一个 SO 问题中了解到,我需要将 x 变量更改为因子,但是当我这样做时,我丢失了 geom_smooth
行。如何更改 x 轴的刻度级别标签而不丢失 geom_smooth
统计信息?
最佳答案
您必须使用scale_x_continuous
,因为您的 a
是一个连续变量。为了定义breaks
的名称,您可以使用labels
参数。
data.frame(a = 1:5, b = 5:9) %>%
ggplot(aes(a, b))+
geom_jitter()+
stat_summary(fun.data = mean_cl_normal)+
geom_smooth(method = 'lm', formula = y~x)+
scale_x_continuous(breaks=1:5, labels=c("a", "b", "c", "d", "f")) +
labs(x="A_Variable", y="B_Variable", title="A plot")
关于r ggplot - 更改 x 轴刻度标签而不丢失 geom_smooth 统计数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59696229/