在制作圖表ggplot2時,在嘗試使用scales.
一個例子:
library("ggplot2")
ggplot(mtcars, aes(drat, mpg)) geom_point()
請注意,此圖在小數點后有一位數字。
但是,我住在荷蘭,我們習慣使用逗號作為小數點。這很容易在scale_x_continuous:
ggplot(mtcars, aes(drat, mpg))
geom_point()
scale_x_continuous(labels = scales::label_number(big.mark = ".", decimal.mark = ","))
這個解決方案讓我感到困擾的是,這也增加了位數:每個標簽的末尾都有一個額外的,相當不必要的 0。當然,這也可以scales::label_number()通過設定來解決,accuracy = 0.1但這需要迭代(繪制和重新繪制以設定更合理的位數)。
是否有修復ggplot使用的默認小數點的選項?我正在尋找一個解決方案
ggplot(mtcars, aes(drat, mpg))
geom_point()
回傳與
ggplot(mtcars, aes(drat, mpg))
geom_point()
scale_x_continuous(labels = scales::label_number(
big.mark = ".",
decimal.mark = ",",
accuracy = 0.1
))
uj5u.com熱心網友回復:
關鍵似乎是format(來自基礎 R)并scales::number使用不同的規則。我們可以恢復使用format...
myf <- function(x, ...) format(x, big.mark = ".", decimal.mark = ",", ...)
ggplot(mtcars, aes(drat, mpg))
geom_point()
scale_x_continuous(labels = myf)
如果您想讓這些標簽成為全域默認值,我認為您可以這樣做:
scale_x_continuous <- function(..., labels = myf) {
do.call(ggplot2::scale_x_continuous, c(list(...), labels = labels))
}
uj5u.com熱心網友回復:
不特定于,ggplot2但您可以使用全域設定輸出小數點字符options(OutDec = ",")。
從幫助頁面:
OutDec:包含單個字符的字串。在輸出轉換中用作小數點的首選字符,即在列印、繪圖、格式和 as.character 中,但在 deparsing 或 sprintf 或 formatC(有時在列印之前使用)時不使用。
library(ggplot2)
options(OutDec= ",")
ggplot(mtcars, aes(drat, mpg))
geom_point()

uj5u.com熱心網友回復:
一個更通用的解決方案是撰寫一個{scales}兼容的標簽函式label_format(),在后臺呼叫base::format(),然后使用荷蘭標點符號約定制作一個專門的版本。
library(ggplot2)
library(scales)
ggplot(mtcars, aes(drat, mpg))
geom_point()
# Use base::format as a {scales}-compatible labels function
label_format <- function(...) {
function(x) do.call(format, c(list(x = x), list(...)))
}
# Specialized version for Dutch punctuation
label_format_NL <- function(...) {
label_format(big.mark = ".", decimal.mark = ",", ...)
}
ggplot(mtcars, aes(drat, mpg))
geom_point()
scale_x_continuous(labels = label_format_NL())
如果您不喜歡為每個軸指定標簽,您可以ggplot2::continuous_scale像這樣覆寫,例如
continuous_scale <- function(...) {
do.call(
ggplot2::continuous_scale,
c(list(labels = label_format_NL()), list(...))
)
}
ggplot(mtcars, aes(drat, mpg))
geom_point()
就個人而言,我會使用顯式scale_AESTHETIC_continous(labels = label_format_NL()),因為這會使您的更改保持本地化。覆寫options()orcontinuous_scale()是全域變數的道德等價物,不推薦。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443268.html
上一篇:如何更改資料圖上點的顏色?
