首页 > 解决方案 > 在 ggplot2 中添加标签和更改 x 轴比例

问题描述

感谢这个论坛的帮助,我设法使用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")

标签: rggplot2

解决方案


对于您的问题 1),一种可能的解决方案是使用geom_text_repelfrom ggrepelpackage 添加文本标签。然而,你必须决定你想把它放在哪里(这里我选择 1965)。

对于您的问题 2),您可以简单地添加breaksscale_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)

在此处输入图像描述

它回答了你的问题吗?


推荐阅读