用样本数据:
df <- structure(list(date = c("2021-10-1", "2021-10-2", "2021-10-3",
"2021-10-4", "2021-10-5", "2021-10-6", "2021-10-7", "2021-10-8",
"2021-10-9", "2021-10-10", "2021-10-11", "2021-10-12", "2021-10-13",
"2021-10-14"), value = c(190.3, 174.9, 163.2, 168.4, 168.6, 168.2,
163.5, 161.6, 172.9, 166.5, 175.2, 197.7, 212.1, 177.9), type = c(1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L)), class = "data.frame", row.names = c(NA,
-14L))以及下面的代码:
ggplot(data = df,
aes(x=date, y=value, group=type, color = type, fill = type)) +
geom_area(alpha=0.4, position = "identity") +
theme(
text = element_text(size=20),
# plot.margin=unit(c(1, 1, 1.5, 1.2),"cm")
# top, right, bottom, left
# plot.margin=unit(c(0, 1.2, 1.5, 10), "pt")
plot.margin=unit(rep(1, 4),'lines')
) +
scale_y_continuous(breaks = range(df$value)) +
scale_x_date(breaks = range(df$date)) +
geom_hline(yintercept=c(min(df$value), max(df$value)), linetype='solid', col=colors[1]) +
geom_text(aes(label = ifelse(date %in% max(date), as.character(date), ""), y = max(value)), color = colors[3], vjust=-0.2, hjust=1, size=6)退出:

正如您所看到的,红色框中的日期不在绘图中,我试图通过向plot.margin=unit(c(1, 1, 1.5, 1.2), "cm")、plot.margin=unit(c(0, 1.2, 1.5, 10), "pt")、plot.margin=unit(rep(1, 4),'lines')等添加theme() (甚至是负值)来调整页边距,但我没有成功。
我知道unit中的四个值表示top, right, bottom, left,但我找不到正确调整它们的方法。
有人能帮忙吗?请提前表示衷心的感谢。
发布于 2021-11-17 12:12:28
一种解决方案是对scale函数使用expand参数。该参数采用“扩展向量”,用于在数据和轴之间添加一些空间。
通过复制您的代码,我能够通过将expand = expansion(mult = c(0, 0.1), add = c(1, 0))添加到scale_y_continuous()来可视化日期(在范围内)。
请注意,我还使用expansion()函数来创建扩展向量,它将只展开y轴顶部,使我们能够完全可视化日期。
所以守则是:
ggplot(data = df,
aes(x=date, y=value, group=type, color = type, fill = type)) +
geom_area(alpha=0.4, position = "identity") +
theme(
text = element_text(size=20),
# plot.margin=unit(c(1, 1, 1.5, 1.2),"cm")
# top, right, bottom, left
# plot.margin=unit(c(0, 1.2, 1.5, 10), "pt")
plot.margin=unit(rep(1, 4),'lines')
) +
scale_y_continuous(breaks = range(df$value),
expand = expansion(mult = c(0, 0.1), add = c(1, 0))) +
scale_x_date(breaks = range(df$date)) +
geom_hline(yintercept=c(min(df$value), max(df$value)), linetype='solid', col="grey40") +
geom_text(aes(label = ifelse(date %in% max(date), as.character(date), ""), y = max(value)), color = "grey50", vjust=-0.2, hjust=1, size=6)退出:

下面是有关此参数和expansion()的更多信息
https://stackoverflow.com/questions/70003394
复制相似问题