r ggplot - 更改 x 轴刻度标签而不丢失 geom_smooth 统计数据

标签 r ggplot2

我制作了一个散点图并在上面画了一条线;现在我需要更改 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)

enter image description here

这还不错,但我需要更改 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"))

enter image description here

这不起作用。我从另一个 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")

enter image description here

关于r ggplot - 更改 x 轴刻度标签而不丢失 geom_smooth 统计数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59696229/

相关文章:

r - 在 R 中排列 4 个 plotly 饼图

r - 如何从具有离散轴的ggplot中删除x值?

r - 黄土复制 geom_smooth 的置信区间/带

r - 如何在 dplyr 的 do() 输出上使用 coef()

r - 仅适用于数据集列的特定数字的科学记数法

r - 通过 RCurl 从 ftp 下载压缩文件

R:使用 Alpha 控制填充

r - Shiny +ggplot : How to subset reactive data object?

R httr 包 - 使用 body 向 API 发出 POST 请求

r - GitHub 中的 Markdown 公式展示