背景:有時我只需要更改繪圖的標簽(例如更改語言),但我不想再次制作整個繪圖,因為在某些情況下代碼可能很長。
問題:它們至少有兩種定義美學標簽的方法:
- 與功能
ggpot2::labs(x = ..., y = ...)和, - 使用
namescales 函式的引數ggplots::scale_*_*(name = ...)
p根據下面的示例,對于 plot ,似乎p labs()可以覆寫用labs()函式定義的實驗室,但不能覆寫用 定義的實驗室scale_*_*(name = ...)。
問題:如何避免這種行為?這是一個錯誤還是我做錯了什么?
例子:
這是按預期作業的:
library(ggplot2)
# This is working as expected
p1 <- ggplot(data = iris, aes(x = Sepal.Width, y = Petal.Width))
scale_x_continuous()
scale_y_continuous()
labs(x = "A name",
y = "Another name")
p1
# trying to change the labs without making the plot again
p1 labs(
x = "The new x title",
y = "The new y title"
)
雖然這不會:
library(ggplot2)
# This is not working
p2 <- ggplot(data = iris, aes(x = Sepal.Width, y = Petal.Width))
scale_x_continuous(name = "A name")
scale_y_continuous(name = "Another name")
p2
p2 labs(
x = "The new x title",
y = "The nex y title"
)
uj5u.com熱心網友回復:
這只是解釋正在發生的事情。有多種方法可以在繪圖中設定標簽,它們具有不同的優先級。以下是從高到低的優先級。
(0。在某些尺度擴展中,該make_title()方法可以被覆寫。但這通常不適用于絕大多數尺度。我知道這樣的尺度正好為 0,但這是理論上的可能性。)
- 指南標題。
- 比例名稱。
labs()功能。- 中捕獲的運算式
aes()。
大多數消歧發生在這行ggplot2 源代碼中,其中優先級 1-3 已解決。該labs()函式本質上所做的是覆寫從捕獲的運算式中自動生成的標簽,從而使 (3) 優先于 (4)。
嘗試注釋掉下面情節的某些部分以仔細檢查自己。
library(ggplot2)
df <- iris
names(df)[1] <- "Last Priority"
ggplot(df, aes(`Last Priority`, Sepal.Width))
scale_x_continuous(
name = "Second Priority",
guide = guide_axis(title = "First priority")
)
labs(x = "Third Priority")
因此,覆寫 x 軸標題的最佳選擇是使用:
plot guides(x = guide_axis(title = "My new title"))
由于軸指南通常是guide_axis()或guide_none(),因此您在大多數情況下都有很大的機會進行此作業(除非繪圖沒有軸)。此外,如果您有一個函式為 x 生成具有預定義比例的繪圖,這應該沒問題(除非他們在指南中設定了特定選項)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482740.html
上一篇:如何去除直方圖中的低頻bin
下一篇:不能讓R在幾年之間做一條線
