我正在嘗試使用 scales 包將美元格式添加到facet wrap 圖scales::dollar_format()的單個圖( )中Sales
z <- data.frame(months = month.name, sales = runif(12, min = 3000000, max = 60000000), cases = round(runif(12, min = 100, max = 1000),0)) %>% pivot_longer(!months, names_to = "variable", values_to = "metric")
ggplot(data = z,
aes(x = months, y = metric))
geom_bar(stat = 'identity')
facet_wrap(~ variable, ncol = 1, scales = "free_y")
我試過使用scale_y_continuous(labels = scales::dollar_format()),但它顯然將它添加到兩者中。
如何將其僅添加到銷售圖而不是案例圖?
uj5u.com熱心網友回復:
在香草 ggplot2 中沒有優雅的方法可以做到這一點。在您的特定情況下,因為您的兩個比例具有非常不同的范圍,您可以通過提供一個有條件地格式化標簽的函式來共同破解解決方案。
library(ggplot2)
library(tidyr)
z <- data.frame(months = month.name, sales = runif(12, min = 3000000, max = 60000000), cases = round(runif(12, min = 100, max = 1000),0)) %>%
pivot_longer(!months, names_to = "variable", values_to = "metric")
p <- ggplot(data = z,
aes(x = months, y = metric))
geom_bar(stat = 'identity')
facet_wrap(~ variable, ncol = 1, scales = "free_y")
p scale_y_continuous(
labels = ~ if (any(.x > 1e3)) scales::dollar(.x) else .x
)

但是,如果您的情況變得更復雜,您可以使用ggh4x::facetted_pos_scales()為特定面板指定特定比例。(免責宣告:我是ggh4x的作者)
p ggh4x::facetted_pos_scales(y = list(
variable == "sales" ~ scale_y_continuous(labels = scales::dollar_format())
))

由reprex 包于 2022-03-09 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443285.html
下一篇:雙條形圖比較兩個分類變數
