R语言 是否有方法更改由geom_label创建的长方体的线型?

w46czmvw  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(110)

我在两个位置创建了一个graph的空气温度,在图上用实线(位置1)和虚线(位置2)表示。我添加了geom_label注解,以文本形式显示最低和最高温度,我真的希望文本周围的框与图上已有的线型相对应(即位置1标签的实心框;位置2标签的虚线框)。
代码方面,我目前有

ggplot() +
  geom_line(data = sum_BHBM3, aes(x = MM, y = minATMP), col = "dodgerblue2") +
  geom_line(data = sum_44013, aes(x = MM, y = meanATMP), col = "black") +
  geom_line(data = sum_44013, aes(x = MM, y = maxATMP), col = "firebrick3") +
  geom_line(data = sum_BUZM3, aes(x = MM, y = minATMP), col = "dodgerblue2", linetype = "22") +
  geom_line(data = sum_BUZM3, aes(x = MM, y = meanATMP), col = "black", linetype = "22") +
  geom_line(data = sum_NWPR1, aes(x = MM, y = maxATMP), col = "firebrick3", linetype = "22") +
  annotate("label", label = "10-yr min: -21.9°C", col = "dodgerblue2", x = 3.75, y = -21) +
  annotate("label", label = "10-yr max: 30.1°C", col = "firebrick3", x = 7.9, y = 25) +
  annotate("label", label = "10-yr min: -16.5°C", col = "dodgerblue2", x = 2, y = -5) +
  annotate("label", label = "10-yr max: 35.5°C", col = "firebrick3", x = 4.4, y = 34.5)

字符串
...
我尝试将linetype = "22"添加到annotate行中以创建虚线轮廓,如

annotate("label", label = "10-yr min: -16.5°C", col = "dodgerblue2", x = 2, y = -5, linetype = "22")


但是它产生“未知参数”警告消息,因此看起来是无效的。我在网上也找不到任何关于这种情况的资源。
是否有方法将标签几何图形周围框的线型设置为虚线?

hec6srdp

hec6srdp1#

您可以绘制圆角矩形,然后文本标签。使用strwidth来测量字符串-这允许框很好地适合它们:

library(tidyverse)

mtcars %>%
  slice_head(n = 8) %>%
  rownames_to_column() %>%
  mutate(strwidth = strwidth(rowname)/20) %>%
  mutate(xmin = wt - strwidth, 
         xmax = wt + strwidth, 
         ymin = mpg - 0.4,
         ymax = mpg + 0.4) %>%
  mutate(cyl = factor(cyl)) %>%
  ggplot(aes(wt, mpg, label = rowname)) +
  statebins:::geom_rrect(aes(xmin = xmin, xmax = xmax, ymin = ymin, 
                             ymax = ymax, linetype = cyl), 
                         fill = "white", color = "black",
           radius = unit(0.4, "lines"), size = 1) +
  geom_text()

字符串
x1c 0d1x的数据

0dxa2lsx

0dxa2lsx2#

看起来并不是这样的(如果没有破解ggplot2或找到其他人定义的替代geom)。这里的内部代码显示,向下传递的唯一矩形格式信息是科洛、填充和线宽。

rect.gp = gpar(
          col = if (isTRUE(all.equal(label.size, 0))) NA else row$colour,
          fill = alpha(row$fill, row$alpha),
          lwd = label.size * .pt
        )

字符串
我现在能得到的最接近的是一个hackytile + text组合(将这两个组合成一个函数是有意义的,但有点棘手)

ggplot(data.frame(x = 1:10, y = 1:10), aes(x, y)) + geom_point() + 
      annotate("tile", x = 5, y = 5, width = 1, height = 0.5, 
                  lwd = 1, lty = 3, fill = "white", col = "red") +
      annotate("text", label = "hello", x = 5, y = 5)

相关问题