r - 在 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))
我在下面插入了我的代码。我想做的是
- 为绘图区域内的平均线和五分位线添加标签。
- 它目前将 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),一种可能的解决方案是使用geom_text_repel
from ggrepel
package 添加文本标签。然而,你必须决定你想把它放在哪里(这里我选择 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)
它回答了你的问题吗?
推荐阅读
- laravel - 在 Chart.js 中使用动态数据将起始值设置为“0”
- arrays - 在 FORTRAN-77 中传递二维数组的子数组
- webassembly - 占用空间小的 WebAssembly 语言
- dafny - 关于 dafny 在 seq 中证明引理的问题
- c# - 使用 c# 将图像的完整路径插入 MySQL
- android - UI 未显示在片段中(RecyclerView)
- javascript - 单击内部按钮时防止单击父A标签
- assembly - 在汇编宏的情况下如何避免名称冲突
- windows - 绕过除 ACL 之外的 WindowsApps 文件夹保护
- java - 为什么我的程序在 Eclipse 上运行 java 程序时生成“java.lang.NoClassDefFoundError: Hi”