简体   繁体   English

在 ggplot2 中添加标签和更改 x 轴刻度

[英]Adding labels and changing x-axis scale in ggplot2

Thanks to help from this forum, I managed to plot a mean line and a quintile line using ggplot2 .感谢这个论坛的帮助,我设法使用 plot 平均线和五分位数线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))

I have inserted my code below.我在下面插入了我的代码。 What I would like to be able to do is我想做的是

  1. Add a label to the mean and quintile lines within the plot area.将 label 添加到 plot 区域内的平均线和五分位线。
  2. It currently breaks up the x-axis scale as 20-year intervals.它目前将 x 轴刻度分解为 20 年间隔。 So 1940, 1960 etc. Can I have it be a narrower scale so every 5 years is a separate labeled point on the x-axis?所以 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")

For your question 1), one possible solution is to add text label using geom_text_repel from ggrepel package.对于您的问题 1),一种可能的解决方案是使用来自geom_text_repel ggrepel的 geom_text_repel 添加文本 label。 However, you will have to decide where you want to place it (here I choose 1965).然而,你必须决定你想把它放在哪里(这里我选择 1965)。

For your question 2), you can simply add breaks into scale_x_continuous .对于您的问题 2),您可以简单地在scale_x_continuous中添加breaks

Altogether, you can do:总之,你可以这样做:

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)

在此处输入图像描述

Does it answer your question?它回答了你的问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM