R 中的 scale_y_continuous 函式
-
使用
scale_y_continuous將 Y 軸標籤列印為 R 中的百分比 -
使用
scale_y_continuous設定 R 中 Y 軸的縮放比例 -
使用
scale_y_continuous刪除 R 中 Y 軸上的標籤 -
在 R 中使用
scale_y_continuous使用自定義值修改 Y 軸標籤
本文將介紹 R 中的 scale_y_continuous 函式。
使用 scale_y_continuous 將 Y 軸標籤列印為 R 中的百分比
scale_y_continuous 用於設定連續 y 軸比例美學的值。該函式是 ggplot2 包的一部分,它主要與 ggplot 物件一起使用來修改要繪製的圖形的不同引數。此示例演示如何使用 scale_y_continuous 將 Y 軸標籤列印為百分比值。請注意,堆疊條形圖是使用 geom_col(position = "fill") 函式呼叫建立的,百分比是使用 scales::percent 函式作為 labels 引數值列印的。由於我們使用 library 呼叫包含了 scales 包,因此可以在此指令碼的範圍內使用 percent 表示法引用它。
library(ggplot2)
library(gridExtra)
library(scales)
p1 <- ggplot(OrchardSprays, aes(x = rowpos, y = decrease, fill = treatment)) +
geom_col(position = "fill")
p2 <- ggplot(OrchardSprays, aes(x = rowpos, y = decrease, fill = treatment)) +
geom_col(position = "fill") +
scale_y_continuous(labels = percent)
grid.arrange(p1, p2, ncol = 2, nrow =2)

使用 scale_y_continuous 設定 R 中 Y 軸的縮放比例
還可以利用 scale_y_continuous 設定 y 軸比例和增量值以列印下一個標籤。seq 函式用於將數字序列傳遞給 scale_y_continuous 呼叫中的 breaks 引數。它將數字解釋為 seq(from, to, by= ) 表示。
library(ggplot2)
library(gridExtra)
library(scales)
p1 <- ggplot(OrchardSprays, aes(x = rowpos, y = decrease, fill = treatment)) +
geom_col(position = "fill")
p2 <- ggplot(OrchardSprays, aes(x = rowpos, y = decrease, fill = treatment)) +
geom_col(position = "fill") +
scale_y_continuous(labels = percent)
p3 <- ggplot(OrchardSprays, aes(x = treatment, y = decrease)) +
geom_point(colour = "blue")
p4 <- ggplot(OrchardSprays, aes(x = treatment, y = decrease)) +
geom_point(colour = "brown") +
scale_y_continuous(breaks = seq(0, 150, 10))
grid.arrange(p1, p2, p3, p4, ncol = 2, nrow =2)

使用 scale_y_continuous 刪除 R 中 Y 軸上的標籤
或者,我們可以使用 scale_y_continuous 函式完全刪除 y 軸上的標籤。為此,我們需要將 NULL 值作為 breaks 引數傳遞。請注意,我們繪製了兩個圖形與 grid.arrange 函式進行視覺比較。
library(ggplot2)
library(gridExtra)
p3 <- ggplot(OrchardSprays, aes(x = treatment, y = decrease)) +
geom_boxplot(fill = "cyan")
p4 <- ggplot(OrchardSprays, aes(x = treatment, y = decrease)) +
geom_boxplot(fill = "pink") +
scale_y_continuous(breaks = NULL)
grid.arrange(p3, p4, ncol = 2, nrow =2)

在 R 中使用 scale_y_continuous 使用自定義值修改 Y 軸標籤
可以混合之前的一些方法以形成更高階的 y 軸美學格式。在以下程式碼片段中,我們明確指定要列印的多個標籤,並同時使用 labels 引數為它們定義新值。請注意,新值只是相應數字的十六進位制數字符號。最後,我們使用給定的字串和 x 軸重新命名 y 軸比例,這是使用 scale_x_discrete 函式完成的。
library(ggplot2)
library(gridExtra)
p3 <- ggplot(OrchardSprays, aes(x = treatment, y = decrease)) +
geom_boxplot(fill = "cyan")
p4 <- ggplot(OrchardSprays, aes(x = treatment, y = decrease)) +
geom_boxplot(fill = "pink") +
scale_y_continuous(
breaks = c(50, 60, 70, 80, 90, 100, 110),
labels = c("32", "3C", "46", "50", "5A", "64", "6E"),
name = "Decrease\n(hex)") +
scale_x_discrete(name = "Treatment")
grid.arrange(p3, p4, ncol = 2, nrow =2)

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu
