我只想繪制我的資料的一個子集,依賴于另一列。我想在 ggplot 中做到這一點,而不是通過對我的資料進行子集化。舉個簡單的例子:
ggplot(mtcars, aes(x=hp, y=mpg)
geom_point()
我如何讓 geom_point 僅使用 cyl == 4 繪制點?
在我的真實資料中,它取決于另一列的值為 TRUE
uj5u.com熱心網友回復:
您可以使用 dplyr 包中的過濾器函式,然后將結果直接通過管道傳輸到 ggplot 函式中。
library(dplyr)
mtcars %>% filter(cyl==4) %>%
ggplot( aes(x=hp, y=mpg))
geom_point()
編輯:
對于使用相同資料的不同子集的更復雜的問題,需要使用 Geoms 呼叫中的“資料”選項來重新定義資料集。
library(dplyr)
mtcars %>% filter(cyl==4) %>%
ggplot( aes(x=hp, y=mpg))
geom_point(color="red")
geom_line(aes(x=hp, y=mpg), data = filter(mtcars, cyl==6))
uj5u.com熱心網友回復:
看起來這可以用 geom_point(data = . %>% filter(newcol>4), color="red")
uj5u.com熱心網友回復:
在這種情況下,我認為最好filter在單個幾何圖層中執行 ing,因為它們都是同一資料源的不同子集。為了防止%>%作為第一個引數輸入的輸出,您需要將ggplot()呼叫包含在花括號中{},然后還將管道輸出包裝在花括號中,如下所示{.}:
{magrittr} 管道的這種有點不直觀的行為在這里被簡單地記錄了下來。
filter您可以通過將 then 與邏輯 OR ( |) 或 AND ( &) 運算子連接來組合運算中的多個條件。
library(tidyverse)
mtcars %>%
mutate(newcol = cyl * wt) %>%
rownames_to_column("car") %>%
{
ggplot()
geom_point(data = {.} %>% filter(cyl > 4 | qsec < 17),
aes(x = hp, y = mpg))
geom_text(data = {.} %>% filter(newcol < 10 | disp < 90),
aes(x = hp, y = mpg, label = car))
}

由reprex 包(v2.0.1)創建于 2022-02-19
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/428864.html
下一篇:ggplot2運行幾分鐘而不繪圖
