[英]How do I add labels to both extremities of my axes?
你可以尝试这样的事情:
library(dplyr)
library(ggplot2)
mtcars %>% ggplot(aes(mpg,hp)) +
geom_point() + annotate("text", x = 33, y = 10,
label = "MPG increases",
hjust=1.1, vjust=-1.1, col="black",
cex=5, fontface = "bold", alpha = 0.8)+
annotate("text", x = 17, y = 10,
label = "MPG decreases",
hjust=1.1, vjust=-1.1, col="black",
cex=5, fontface = "bold", alpha = 0.8)+
annotate("text", x = 17, y = 100,
label = "HP decreases",
hjust=1.1, vjust=-1.1, col="black",
cex=5, fontface = "bold", alpha = 0.8)+
annotate("text", x = 17, y = 310,
label = "HP increases",
hjust=1.1, vjust=-1.1, col="black",
cex=5, fontface = "bold", alpha = 0.8)
这是在数据的最大和最小限制范围内执行此操作的一种方法。 并接受@Tjebo 的建议,将标签文本包含在数据框中。
尽管问题中没有包含箭头,以查看这是否有助于区分 HP 和 MPG 减少标签。 很容易忽略此代码。
如果您想定期使用此演示文稿,则需要制作 function。
library(ggplot2)
library(tibble)
mtcars %>%
ggplot(aes(mpg,hp)) +
geom_point()+
geom_text(data = df_lab, aes(x, y, label = lab), vjust = df_lab$vj, hjust = df_lab$hj)+
geom_segment(data = df_ar, aes(x = x, y = y, xend = xend, yend = yend),
lineend = "square", linejoin = "mitre", size = 1, arrow = arrow(length = unit(2, "mm")))
# tibble for labels
df_lab <-
tibble(lab = c("HP increases", "HP decreases", "MPG decreases", "MPG increases"),
x = c(rep(min(mtcars$mpg), 3), max(mtcars$mpg)),
y = c(max(mtcars$hp), rep(min(mtcars$hp), 3)),
vj = rep(c("bottom", "top") , each = 2),
hj = c(rep("left", 3), "right"))
# postitioning helpers for arrows
x_len <- 2
y_len <- 40
y_off <- 15
x_off <- 0.5
# tibble for arrows
df_ar <-
tibble(xend = c(rep(min(mtcars$mpg) - x_off, 2), min(mtcars$mpg), max(mtcars$mpg)),
yend = c(max(mtcars$hp), min(mtcars$hp), rep(min(mtcars$hp) - y_off, 2)),
x = c(rep(min(mtcars$mpg) - x_off, 2), min(mtcars$mpg) + x_len, max(mtcars$mpg) - x_len),
y = c(max(mtcars$hp) - y_len, min(mtcars$hp) + y_len, rep(min(mtcars$hp) - y_off, 2)))
由代表 package (v0.3.0) 于 2020 年 5 月 12 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.