library(tidyverse)
df <- data.frame(x = c(1, 2, 3, 4),
y1 = c(1, 3, 2, 4),
y2 = c(3000, 2000, 4000, 1000))
label_1 = c("1", "2", "3") %>% format(width = 5, justify = "right")
label_2 = c("1000", "2000", "3000") %>% format(width = 5, justify = "right")
p1 <- df %>% ggplot(aes(x = x, y = y1))
geom_line()
scale_y_continuous(breaks = c(1, 2, 3),
labels = label_1)
p2 <- df %>% ggplot(aes(x = x, y = y2))
geom_line()
scale_y_continuous(breaks = c(1000, 2000, 3000),
labels = label_2)
p1
p2

在上面的代碼中,我嘗試制作p1和p2具有相同長度的y-axis標簽, by format(width = 5)。在實際圖中,標簽p1仍然比標簽短p2。
通過反復試驗,我在設定時得到了正確的長度width =8。
label_3 = c("1", "2", "3") %>% format(width = 8, justify = "right")
p1 <- df %>% ggplot(aes(x = x, y = y1))
geom_line()
scale_y_continuous(breaks = c(1, 2, 3),
labels = label_3)
p1

有人可以解釋一下或指導我之前的相關帖子嗎?
uj5u.com熱心網友回復:
常規空格與數字的寬度不同(在非等寬字體中)。Unicode 有一個具有“表格寬度”的“圖形空間”,即與數字相同的寬度。如果您創建一個用表格寬度 ( ) 替換空格的輔助函式\u2007,則兩個圖的 y 軸大小應該相同。功能:
pad_numbers <- function(x, width, justify = "right") {
x <- format(x, width = width, justify = justify)
gsub(" ", "\u2007", x)
}
在行動:
library(tidyverse)
df <- data.frame(x = c(1, 2, 3, 4),
y1 = c(1, 3, 2, 4),
y2 = c(3000, 2000, 4000, 1000))
label_1 = c("1", "2", "3") %>% pad_numbers(width = 5, justify = "right")
label_2 = c("1000", "2000", "3000") %>% pad_numbers(width = 5, justify = "right")
p1 <- df %>% ggplot(aes(x = x, y = y1))
geom_line()
scale_y_continuous(breaks = c(1, 2, 3),
labels = label_1)
p2 <- df %>% ggplot(aes(x = x, y = y2))
geom_line()
scale_y_continuous(breaks = c(1000, 2000, 3000),
labels = label_2)
p1

p2

由reprex 包于 2022-02-17 創建(v2.0.1)
Lastly, if you want the y-axis to have the same width for plot composition purposes, I recommend the {ragg} package, which does a good job at aligning the panels between two plots. This wouldn't require the helper function we wrote at the beginning.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/427633.html
下一篇:R中帶有ggplot2的箱線圖
