感谢这个论坛的帮助,我成功地使用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))
我已在下面插入了我的代码。我希望能够做的是
- 向绘图区域内的平均线和五分位数线添加标签。
- 目前,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)
它能回答你的问题吗?
关于r - 在 ggplot2 中添加标签并更改 x 轴刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61461359/