讓我看看我有以下兩個圖。
library(data.table)
library(ggplot2)
df_one <- data.table(
x = c(1, 1, 3),
y = c(10, 20, 30)
)
df_two <- data.table(
x = c(1, 2, 3),
y = c(1000, 1600, 3100)
)
df_one %>% ggplot(aes(x, y)) geom_point() geom_line()
df_two %>% ggplot(aes(x, y)) geom_point() geom_line()
Y 軸上的值因寬度而異。如果我們不知道每個資料集的資訊,如何調整兩個圖以在 Y 上具有相同的標簽寬度。例如,如果我們想將寬度設定為固定數量的字符(10 或 15)。
謝謝
uj5u.com熱心網友回復:
您可以在scale_y_continuous.
例如,對繪圖的這種添加通過在前面添加空格使 y 軸標記為 10 個字符的固定寬度。
df_one %>% ggplot(aes(x, y)) geom_point() geom_line()
scale_y_continuous(labels = function(x) formatC(x, width = 10))

df_two %>% ggplot(aes(x, y)) geom_point() geom_line()
scale_y_continuous(labels = function(x) formatC(x, width = 10))

當然,面板可能仍然無法完美對齊,因為您沒有使用等寬字體。這意味著即使它們的字符數相同,螢屏上的空格和數字也會有不同的寬度。
如果您使用單色字體,這將提供完美對齊:
df_one %>% ggplot(aes(x, y)) geom_point() geom_line()
scale_y_continuous(labels = function(x) formatC(x, width = 6))
theme(axis.text = element_text(family = "mono"))

df_two %>% ggplot(aes(x, y)) geom_point() geom_line()
scale_y_continuous(labels = function(x) formatC(x, width = 6))
theme(axis.text = element_text(family = "mono"))

由reprex 包( v2.0.0 )于 2021 年 11 月 4 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/348074.html
