【问题标题】:How to set dotted line length as less than 1 in ggplot2?如何在ggplot2中将虚线长度设置为小于1?
【发布时间】:2021-10-16 08:13:47
【问题描述】:

我正在尝试使用长度小于 1 的虚线网格线设置主题,但鉴于单位为十六进制,我不确定这是否可行。现在我将线型设置为“11”,而我真的希望它类似于 c("0.5", "1")。

这是我在尝试中引用的 ggplot2 材料:

library(ggplot2)

#A simple plot with manually set dashes.
#The first numeral is units of dash length, the second units in the gap in hexadecimal. 
lty <- c("11", "18", "1f", "81", "88", "8f", "f1", "f8", "ff")
linetypes <- data.frame(y = seq_along(lty), lty = lty) 

ggplot(linetypes, aes(0, y)) + 
  geom_segment(aes(xend = 5, yend = y, linetype = lty)) + 
  scale_linetype_identity() + 
  geom_text(aes(label = lty), hjust = 0, nudge_y = 0.2) +
  scale_x_continuous(NULL, breaks = NULL) + 
  scale_y_reverse(NULL, breaks = NULL)

此处引用:https://cran.r-project.org/web/packages/ggplot2/vignettes/ggplot2-specs.html

【问题讨论】:

  • “当我真的希望它类似于c("0.5", "1")”是什么意思?
  • linetype="11"的含义如下。第一个表示点的长度为 1,第二个表示点的间隙为 1。我想要的是 0.5 的长度和 1 的间隙。
  • 换句话说,您希望破折号的段比宽度高吗?对吗?
  • @JonSpring 我主要是想让点比“1”更窄。不关心点本身的高度与宽度。

标签: r ggplot2


【解决方案1】:

我不知道有一种内置的方法来制作高而不是宽的破折号;在您的示例中使用“11”类型,您自然可以获得的最接近的是 1:1。

这是一个 hack,但它的适应性不是很好,即真的只适用于水平线:

lty <- c("11", "18", "1f", "81", "88", "8f", "f1", "f8", "ff")
linetypes <- data.frame(y = seq_along(lty), lty = lty) 

ggplot(linetypes, aes(0, y)) + 
  geom_segment(aes(xend = 5, yend = y, linetype = lty), size = 3) + 
  geom_segment(aes(xend = 5, y = y+0.14, yend = y+0.14, linetype = lty), size = 3) + 
  scale_linetype_identity() + 
  geom_text(aes(label = lty), hjust = 0, nudge_y = 0.2) +
  scale_x_continuous(NULL, breaks = NULL) + 
  scale_y_reverse(NULL, breaks = NULL)

我怀疑使用ggforce::geom_link 有更好的方法来做到这一点,但我还没有想出来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-29
    • 2016-05-10
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多