【问题标题】:Tick marks either side of dates in ggplot打勾标记ggplot中日期的任一侧
【发布时间】:2021-07-05 22:28:19
【问题描述】:

Ggplot 使用此代码集中添加刻度标记:

tibble(year = 2010:2020, count = sample(1:100, 11)) %>%
  mutate(year = paste0("01/01/", year)) %>%
  mutate(year = dmy(year)) %>%
  ggplot +
  geom_bar(aes(year, count), stat = "identity", width = 240, position = position_dodge(width = 0.1)) +
  scale_x_date(date_labels = "%y", date_breaks = "1 year") +
  scale_y_continuous(limits = c(0,100), expand = c(0, 0)) +
  theme_classic()

但我需要在一年中的任何一侧做记号。我已经在刻度线图中进行了 photoshop 以显示我需要它们的位置。我可以使用什么代码在年份的任一侧添加刻度线?

【问题讨论】:

  • 这需要一些研究,但您可以使用 grid 包来自定义刻度位置。 (用grid.xaxis()创建一个自定义的,或者创建后编辑segments[ticks]图形对象)

标签: r ggplot2 axis-labels


【解决方案1】:

您可以使用geom_segment()自己绘制刻度线,关闭剪切并隐藏默认的。

library(ggplot2)
library(dplyr)
library(lubridate)

tbl <- tibble(year = 2010:2020, count = sample(1:100, 11)) %>%
  mutate(year = paste0("01/01/", year)) %>%
  mutate(year = dmy(year))

ggplot(tbl) +
  geom_bar(aes(year, count), stat = "identity", width = 240, position = position_dodge(width = 0.1)) +
  geom_segment(aes(x = year, xend = year), y = 0, yend = -1, 
               colour ="black", position = position_nudge(x = 240/2)) +
  geom_segment(aes(x = year, xend = year), y = 0, yend = -1, 
               colour ="black", position = position_nudge(x = -240/2)) +
  scale_x_date(date_labels = "%y", date_breaks = "1 year") +
  scale_y_continuous(limits = c(0,100), expand = c(0, 0),
                     oob = scales::oob_keep) +
  coord_cartesian(clip = "off") +
  theme_classic() +
  theme(axis.ticks = element_blank())

reprex package (v1.0.0) 于 2021-04-10 创建

【讨论】:

  • 加载所需的包(c("dplyr", "ggplot2"))比加载整个tidyverse更好。
  • 是的,原则上我同意这一点。但是,每当我因为没有包含库而无法直接复制某人的示例并且遇到我认为是 tidyverse 错误的错误时,我只会加载整个 tidyverse。我的目标是解决问题,我不是自愿抽出时间来追溯问题忘记包含的最少的软件包。
  • 嗯,只需要一分钟或更短的时间 :) 但我同意 OP 应该提供一个完全可重现(处理复制粘贴)的示例,包括所需的库。 +1
猜你喜欢
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 2016-08-24
  • 2018-01-01
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多