This post describes a method在时间序列图上创建一个双线x轴(年在月之下)。不幸的是,我在这篇文章中使用的方法(* 选项2*)与ggsave()
不兼容。
library(tidyverse)
library(lubridate)
df <- tibble(
date = as.Date(41000:42000, origin = "1899-12-30"),
value = c(rnorm(500, 5), rnorm(501, 10))
)
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(
xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60"
) +
scale_x_date(date_labels = "%b", date_breaks = "month", expand = c(0, 0)) +
theme_bw() +
theme(panel.grid.minor.x = element_blank()) +
labs(x = "")
# Get the grob
g <- ggplotGrob(p)
# Get the y axis
index <- which(g$layout$name == "axis-b") # which grob
xaxis <- g$grobs[[index]]
# Get the ticks (labels and marks)
ticks <- xaxis$children[[2]]
# Get the labels
ticksB <- ticks$grobs[[2]]
# Edit x-axis label grob
# Find every index of Jun in the x-axis labels and a year label
junes <- grep("Jun", ticksB$children[[1]]$label)
ticksB$children[[1]]$label[junes] <-
paste0(
ticksB$children[[1]]$label[junes],
"\n ", # adjust the amount of spaces to center the year
unique(year(df$date))
)
# Center the month labels between ticks
ticksB$children[[1]]$label <-
paste0(
paste(rep(" ", 12), collapse = ""), # adjust the integer to center month
ticksB$children[[1]]$label
)
# Put the edited labels back into the plot
ticks$grobs[[2]] <- ticksB
xaxis$children[[2]] <- ticks
g$grobs[[index]] <- xaxis
# Draw the plot
grid.newpage()
grid.draw(g)
# Save the plot
ggsave("plot.png", width = 11, height = 8.5, units = "in")
字符串
保存了一个图,但没有年份。如何从grid.draw(g)
中ggsave()
最终的图?这个grid.draw(g)
图如下所示,但实际的plot.png
文件略有不同,省略了三个年份2012
,2013
和2014
。
的数据
3条答案
按热度按时间mbyulnm01#
字符串
x1c 0d1x的数据
使用
theme_classic()
型
的
添加顶部和最右侧的边框
型
由reprex package(v0.2.1.9000)于2018-10-01创建
vaj7vani2#
取自上面的
Tung
注解。在op的问题中的代码块的末尾添加以下内容。字符串
q0qdq0h23#
在游戏后期,一个不需要使用grobs的简单解决方案是在边距之外使用
geom_text
,并告诉ggplot不要隐藏该空间。因此,在使用
p <- ggplot(df, aes(date, value)) + ...
绘制完图之后,计算数据中每年的平均日期,例如使用years <- df[, .(date = mean(date)), year(date)]
(在这里使用data.table,但如果需要,可以使用整洁的方式),然后字符串
适当调整
vjust
,使其与x标签之间具有所需的间距。现在可以使用
ggsave
保存此图。