我正在嘗試以相當定制的外觀繪制一些東西,其中一個設計指南指出,情節的上限應該有一條網格線,在某種程度上描繪了情節。現在,在 ggplot 中,這應該可以使用limits()和expand()inside來實作scale_y_continuous()。例子:
library(ggplot)
p <- ggplot(data = mpg)
geom_point(mapping = aes(x = displ, y = hwy))
scale_y_continuous(limits = c(0, 50),
expand=expansion())
theme_light()
theme(axis.line = element_line(color = '#000000', size=0.265),
#Ticks
axis.ticks = element_line(color = '#000000', size=0.265),
axis.ticks.length = unit(5, "pt"),
panel.grid.major.y = element_line(color='#7f7f7f', size=0.265),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank(),
panel.border = element_blank())
p
在 RStudio 的繪圖窗格中看起來還不錯:

但是:當我保存 png 時:
ggsave("testplot.png", p)
輸出的左上角如下所示:

我發現這種行為相當莫名其妙,我無法弄清楚,當刻度線不是時,是什么導致網格線被切斷。一種解決方法是稍微擴展 Y 軸
scale_y_continuous(limits = c(0, 50),
expand=expansion(mult=c(0,0.0015)))
這在png中給了我這個:

但我必須說我發現這個解決方案不是很實用。此外,在 RStudio 的繪圖窗格中,Y 軸現在略微延伸到最上面的網格線...
誰能解釋一下,這里發生了什么,有沒有辦法不切斷頂部網格線?
uj5u.com熱心網友回復:
TL;DR:這是因為剪輯。讓我們通過給它額外的粗線來夸大你的情節。
library(ggplot2)
p <- ggplot(data = mpg)
geom_point(mapping = aes(x = displ, y = hwy))
scale_y_continuous(limits = c(0, 50),
expand=expansion())
theme_light()
theme(axis.line = element_line(color = '#000000', size=5),
axis.ticks = element_line(color = '#000000', size=5),
axis.ticks.length = unit(10, "pt"),
panel.grid.major.y = element_line(color='#7f7f7f', size=5),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.minor.y = element_blank(),
panel.border = element_blank())
p

在上圖中,很明顯頂部網格線看起來比其他網格線更細。這是由于面板剪輯,它將面板上的任何內容(包括網格線)剪輯到面板區域。您可以按照以下方式轉動它:
p coord_cartesian(clip = "off")

那已經看起來更好了。作為我們中間注重細節的獎勵,您可以看到軸頂部有一個奇怪的“咬”。這是因為刻度線和軸線在 90 度角下相交,但不是同一條(多邊形)線的一部分(因此沒有連接)。為了使這個角變得漂亮和齊平,您可以設定lineend軸線或刻度。
p coord_cartesian(clip = "off")
theme(axis.line = element_line(colour = "#000000", size = 5,
lineend = "square"))

由reprex 包于 2022-02-15 創建(v2.0.1)
請注意,這給出了明顯的延伸,使 x 軸線比網格線長。您可以通過兩種方式處理此問題:
- You can set this
lineendon the axis ticks instead, but then they might start overlapping with the text. Hence, I recommend you adjust the text margins as well then. - You can set this
lineendon the panel grid lines too.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427653.html
