我正在嘗試使用 R 中內置的資料框“swiss”生成一個圖。我正在嘗試將地毯添加到生育力?教育的圖中,但只為超過 50% 的男性參與的省份繪制地毯農業作為一種職業。這是我到目前為止的代碼:
ggplot(data = swiss)
geom_point(mapping = aes(x = Education, y = Fertility))
geom_smooth(method = "lm", aes(x = Education, y = Fertility), se = FALSE)
geom_smooth(method = "loess", aes(x = Education, y = Fertility,
col = "red"),
linetype = "dotted",
lwd = 2,
se = FALSE)
geom_rug(mapping = aes(x = Education[Agriculture >= 50], y = Fertility[Agriculture >= 50]),
color = "blue")
當我運行此代碼時,我收到錯誤:check_aesthetics() 中的錯誤:美學長度必須為 1 或與資料 (47)、x 和 y 相同。
我知道兩個子集都等于 26,并且我已經嘗試預先設定資料(x 和 y)然后運行代碼,但這給了我在 fortify() 中的錯誤。即使在我將子集資料稱為資料框之后,也會發生 fortify() 錯誤。
我不知道接下來要嘗試什么,所以任何建議都是有幫助的。這是情節應該看起來的樣子以供參考。
預期產出
Yi2T8.png
uj5u.com熱心網友回復:
問題是您對向量進行了子集化。而是將用于的資料子集geom_rug:
library(ggplot2)
ggplot(data = swiss)
geom_point(mapping = aes(x = Education, y = Fertility))
geom_smooth(method = "lm", aes(x = Education, y = Fertility), se = FALSE)
geom_smooth(
method = "loess", aes(
x = Education, y = Fertility,
col = "red"
),
linetype = "dotted",
lwd = 2,
se = FALSE
)
geom_rug(
data = subset(swiss, Agriculture >= 50), mapping = aes(x = Education, y = Fertility),
color = "blue"
)
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'

并且要像您發布的圖片那樣僅在底部顯示地毯,那么您必須設定sides="b":
library(ggplot2)
ggplot(data = swiss)
geom_point(mapping = aes(x = Education, y = Fertility))
geom_smooth(method = "lm", aes(x = Education, y = Fertility), se = FALSE)
geom_smooth(
method = "loess", aes(
x = Education, y = Fertility,
col = "red"
),
linetype = "dotted",
lwd = 2,
se = FALSE
)
geom_rug(
data = subset(swiss, Agriculture >= 50), mapping = aes(x = Education, y = Fertility),
color = "blue",
sides = "b"
)
#> `geom_smooth()` using formula 'y ~ x'
#> `geom_smooth()` using formula 'y ~ x'

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/523483.html
標籤:rggplot2
下一篇:為GG繪圖直方圖著色的問題
