我想設定positon一些條件,但是使用時出現錯誤if_else()。
下面是一個可重現的示例。
我的問題是:
如何position在 ggplot2 中使用條件。
library(dplyr)
pd_ture = position_dodge(.4)
pd_false = position_dodge(.6)
mtcars_true = mtcars %>% mutate(test = TRUE)
mtcars_false =mtcars %>% mutate(test = FALSE)
ggplot(mtcars_true, aes(factor(cyl), fill = factor(vs)))
geom_bar(position = if_else(unique(mtcars_true$test), pd_ture, pd_false))
# Error in true[rep(NA_integer_, length(condition))] :
# object of type 'environment' is not subsettable
ggplot(mtcars_false, aes(factor(cyl), fill = factor(vs)))
geom_bar(position = if_else(unique(mtcars_false$test), pd_false, pd_ture))
# Error in true[rep(NA_integer_, length(condition))] :
# object of type 'environment' is not subsettable
uj5u.com熱心網友回復:
您可以執行此操作,但不能使用if_elseor ifelse,因為它們會將子集運算子應用于 的輸出position_dodge,這不是可子集的。相反,您需要一個很好的老式if(unique(mtcars_true$test)) pd_ture else pd_false:
ggplot(mtcars_true, aes(factor(cyl), fill = factor(vs)))
geom_bar(position = if(unique(mtcars_true$test)) pd_ture else pd_false)

uj5u.com熱心網友回復:
我不認為你能做到這一點。你想要的是這樣的模式:
ggplot(mtcars_true, aes(factor(cyl), fill = factor(vs)))
geom_bar(data = . %>% filter(test), position = pd_ture)
geom_bar(data = . %>% filter(!test), position = pd_false)
但是您設定它的方式,mtcars_true/mt_cars_false并不是為此而設計的。因此,要使當前設定正常作業,您需要:
ggplot(mtcars_true, aes(factor(cyl), fill = factor(vs)))
geom_bar(data = mtcars_true, position = pd_ture)
geom_bar(data = mtcars_false, position = pd_false)
但是 的模式將允許您對當前層/正在饋送data = . %>% [data transforming pipes]的資料的哪一部分進行子集化。geom_*
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483766.html
上一篇:編輯邊際效應圖中置信區間的外觀
