【问题标题】:How does The Economist make these lines near the title using using ggplot?The Economist 如何使用 ggplot 在标题附近制作这些线条?
【发布时间】:2020-11-03 03:02:11
【问题描述】:

我真的很喜欢《经济学人》杂志的美学,我经常使用 theme_economist。但是,我很好奇他们是如何在许多图表的左上角创建红线的。请参阅下图和我圈出的位置。

【问题讨论】:

  • 红线有含义吗? (这对你的问题没有帮助,但我很好奇)
  • 不,我只是觉得它看起来不错而且很专业
  • 如果您可以提供一个简单的、可重现的图表示例,您希望在该图表中添加红线,将会有所帮助。另外,我在您提供的图片中没有看到任何圈出的内容。
  • 是的,抱歉忘了添加那条,我只是在说图表左上角的那条红线

标签: r ggplot2


【解决方案1】:

这个问题混合了“如何在绘图区域之外进行注释”和“如何在 npc 坐标中进行注释”。因此,我提供了两种选择。

不幸的是,两者都需要一些试验和错误才能正确放置片段。对于选项 1,我们必须“猜测”的是 y 坐标,对于选项 2,它是 x!

为了让 y 的猜测工作稍微少一些,我尝试了一种相对于默认轴中断的位置方法。 using the fabulous information from this answer。这当然不是必须的,也可以简单地试错。

对于选项 2,我修改了一个函数 from user Allan Cameron's answer here。他提到了一种计算x和y的方法,我想可以使用标题,然后根据它放置注释。

library(ggplot2)

p <-
  ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  ggtitle("lorem ipsum") +
  theme(plot.margin = margin(t = 1.5, unit = "lines")) # this is always necessary

# OPTION 1
# semi-programmatic approach to figure out y coordinates
y_defaultticks <- with(mtcars, labeling::extended(range(wt)[1], range(wt)[2], m = 5))
y_default <- y_defaultticks[2] - y_defaultticks[1] 
y_seg <- max(mtcars$wt) + 0.75 * y_default

p +
annotate(geom = "segment", x = - Inf, xend = 12, y = y_seg, yend = y_seg, 
         color = "red", size = 5) +
  coord_cartesian(clip = "off", ylim = c(NA, max(mtcars$wt)),
                  xlim = c(min(mtcars$mpg), NA)) 



# OPTION 2
annotate_npc <- function(x, y, height, width, ...) {
  grid::grid.draw(grid::rectGrob(
    x = unit(x, "npc"), y = unit(y, "npc"), height = unit(height, "npc"), width = unit(width, "npc"),
    gp = grid::gpar(...)
  ))
}

p
annotate_npc(x = 0.07, y = 1, height = 0.05, width = 0.05, fill = "red", col = NA)

reprex package (v0.3.0) 于 2021-01-02 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多