我在徘徊是否有可能獲得因子水平和條形填充顏色之間的映射。例如:
library(ggplot2)
library(dplyr)
d <- mtcars %>% mutate_at(vars(am, cyl, carb, gear, vs), as.factor) # make factors from vars
p <- ggplot(
data = d,
aes(x = am, fill = cyl)
) geom_bar()
結果是

現在,我檢查從繪圖構建的物件中的基礎資料
built <- ggplot2::ggplot_build(p)
我可以看到這樣的事情:
> built$data[[1]]
fill y count prop x flipped_aes PANEL group ymin ymax xmin xmax colour size linetype alpha
1 #F8766D 19 3 1 1 FALSE 1 1 16 19 0.55 1.45 NA 0.5 1 NA
2 #00BA38 16 4 1 1 FALSE 1 2 12 16 0.55 1.45 NA 0.5 1 NA
3 #619CFF 12 12 1 1 FALSE 1 3 0 12 0.55 1.45 NA 0.5 1 NA
4 #F8766D 13 8 1 2 FALSE 1 4 5 13 1.55 2.45 NA 0.5 1 NA
5 #00BA38 5 3 1 2 FALSE 1 5 2 5 1.55 2.45 NA 0.5 1 NA
6 #619CFF 2 2 1 2 FALSE 1 6 0 2 1.55 2.45 NA 0.5 1 NA
我的問題是,如何獲得映射到fill美學的因子級別對應于上述資料集中的哪個填充值的明確資訊?我的例子很簡單,但真正的用例是我所有的輸入只是一個 ggplot 類的圖。
uj5u.com熱心網友回復:
library(tidyverse)
d <- mtcars %>% mutate_at(vars(am, cyl, carb, gear, vs), as.factor) # make factors from vars
p <- ggplot(
data = d,
aes(x = am, fill = cyl)
) geom_bar()
q <- ggplot_build(p)
# mappings
q[["plot"]][["mapping"]]
#> Aesthetic mapping:
#> * `x` -> `am`
#> * `fill` -> `cyl`
# fill levels
q[["plot"]][["scales"]][["scales"]][[2]][["palette.cache"]]
#> [1] "#F8766D" "#00BA38" "#619CFF"
# mapped aesthetic levels
q[["plot"]][["scales"]][["scales"]][[2]][["range"]][["range"]]
#> [1] "4" "6" "8"
由reprex 包(v2.0.1)于 2021 年 12 月 14 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/380664.html
上一篇:從串列R中呼叫索引案例
