使用樣本資料:
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,但我沒有找到正確調整它們的方法。
有人可以幫忙嗎?在此表示衷心的感謝。
uj5u.com熱心網友回復:
一種解決方案是使用expandscale 函式的引數。此引數采用“擴展向量”,用于在資料和軸之間添加一些空間。
通過復制您的代碼,我能夠通過添加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():
- ggplot scale_continuous expand 引數如何作業?
- https://www.rdocumentation.org/packages/ggplot2/versions/3.3.5/topics/expansion
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358860.html
