r - 在 ggplot2 中添加标签并更改 x 轴刻度

标签 r ggplot2

感谢这个论坛的帮助,我成功地使用ggplot2绘制了一条平均线和一条五分位数线。

DF<-data.frame(DOB = c(1965, 1 949, 1964, 1979, 1960, 1992, 1991, 1963, 1964, 1992, 1971, 1965),
               trip.duration.hr =c(3.36, 2.25, 5.31, 10.7, 1.96, 4.33, 23.55, 3.92, 5.46, 3.45, 13.72, 7.33))

我已在下面插入了我的代码。我希望能够做的是

  1. 向绘图区域内的平均线和五分位数线添加标签。
  2. 目前,X 轴刻度以 20 年为间隔。所以 1940 年、1960 年等。我可以将其缩小为每 5 年一次吗 x 轴上有一个单独的标记点吗?
    ggplot(DF, aes(x=DOB, y=trip.duration.hr)) +
      geom_jitter(alpha=1/10) +
      geom_line(stat = 'summary', fun.y = "mean", color="orange", size=1) +
      geom_line(stat = 'summary', fun.y = "quantile", fun.args = list(probs = .9), linetype=2, color="red")

最佳答案

对于您的问题 1),一种可能的解决方案是使用 ggrepel 包中的 geom_text_repel 添加文本标签。但是,您必须决定将其放置在何处(此处我选择 1965)。

对于您的问题 2),您只需将 breaks 添加到 scale_x_continuous 中即可。

总而言之,您可以执行以下操作:

library(ggplot2)
library(ggrepel)

ggplot(DF, aes(x=DOB, y=trip.duration.hr)) +
  geom_jitter(alpha=1/10) +
  geom_line(stat = 'summary', fun = "mean", color="orange", size=1) +
  geom_line(stat = 'summary', fun = "quantile", fun.args = list(probs = .9), linetype=2, color="red")+
  scale_x_continuous(breaks = seq(1950,1995, by = 5))+
  geom_text_repel(data = subset(aggregate(trip.duration.hr ~ DOB, DF, mean), DOB == 1965),
                  label = "Mean", color = "orange", nudge_x = 5, nudge_y = 1)+
  geom_text_repel(data = subset(aggregate(trip.duration.hr ~ DOB, DF, "quantile", probs = 0.9), DOB == 1965),
                  label = "quantile", color = "red", nudge_x = -5, nudge_y = 1)

enter image description here

它能回答你的问题吗?

关于r - 在 ggplot2 中添加标签并更改 x 轴刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61461359/

相关文章:

r - 如何在ggplot中将颜色代码转换为字母标签

返回值的所有可能组合

Beaker Notebook 中的 R-scatterplot3d 渲染

r - 是否可以使用 geom_text 将文本放在每个构面面板下方并将其与刻度线对齐?

r - 将标签添加到由 grid.arrange 从多个绘图制作的绘图

r - 使用自定义渐变填充直方图箱

r - ggplot 颜色条标签日期格式

r - 通过公共(public)列R合并不同长度的表

r - 基于更平等条件的不精确连接数据

r - 使用 dplyr 为 Group 中的不同值分配唯一 ID