R studio 添加 geom_abline 指定截距
R studio add geom_abline with specified intercept
无论 x 和 y 比例如何,我都希望有一条线以 45 度角穿过图表。在这个例子中,abline 的截距应该在 x=-3 和 y=-0.5.
附近
下面几行代码:
x <- seq(1,10,1)
y <- sample(1:100, 10, replace=T)
df <- data.frame(x,y)
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_abline(slope = 45) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 10), limits = c(-10,10)) +
scale_x_continuous(breaks = scales::pretty_breaks(n = 10), limits = c(-2,10))
您只需添加
ggplot2::annotation_custom(grid::linesGrob())
你的阴谋。
所以你可以这样做:
x <- rnorm(100)
y <- rnorm(100)
df <- data.frame(x,y)
ggplot(df, aes(x=x, y=y)) +
geom_point() +
ggplot2::annotation_custom(grid::linesGrob())
或这个
ggplot(df, aes(x=x)) +
geom_histogram() +
ggplot2::annotation_custom(grid::linesGrob())
如果你想改变线条的外观,你需要改变 grob:
ggplot(df, aes(x=x, y=y)) +
geom_point() +
ggplot2::annotation_custom(grid::linesGrob(gp = grid::gpar(col = "red", lty = 2)))
无论 x 和 y 比例如何,我都希望有一条线以 45 度角穿过图表。在这个例子中,abline 的截距应该在 x=-3 和 y=-0.5.
附近下面几行代码:
x <- seq(1,10,1)
y <- sample(1:100, 10, replace=T)
df <- data.frame(x,y)
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_abline(slope = 45) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 10), limits = c(-10,10)) +
scale_x_continuous(breaks = scales::pretty_breaks(n = 10), limits = c(-2,10))
您只需添加
ggplot2::annotation_custom(grid::linesGrob())
你的阴谋。
所以你可以这样做:
x <- rnorm(100)
y <- rnorm(100)
df <- data.frame(x,y)
ggplot(df, aes(x=x, y=y)) +
geom_point() +
ggplot2::annotation_custom(grid::linesGrob())
或这个
ggplot(df, aes(x=x)) +
geom_histogram() +
ggplot2::annotation_custom(grid::linesGrob())
如果你想改变线条的外观,你需要改变 grob:
ggplot(df, aes(x=x, y=y)) +
geom_point() +
ggplot2::annotation_custom(grid::linesGrob(gp = grid::gpar(col = "red", lty = 2)))