問題
我有一些資料點存盤在data.frame中,有三個變數:x、y和gender。我的目標是在散點圖上畫出幾條普遍擬合的線和專門為男性/女性擬合的線,并按性別對點進行著色。這聽起來很容易,但有些問題卻一直存在。
我目前所做的是為每個模型使用一組新的x,并預測y,將擬合線合并到一個data.frame中,然后將寬轉換為長,將其模型名稱作為第三個var(來自這個帖子。
另一種方法的代碼(省略了兩行),它生成了同色圖例和多色圖:
ggplot(data = prdf。 aes(x = x, y = fit)) = fit) # prdf和prdm只是包含不同模型的x和擬合值的資料框架
geom_line(aes(lty="女")。 colour = "chocolate")
geom_line(data = prdm, aes(x = x, y = fit, lty="Male")。 color = "darkblue")
geom_point(data = data, aes(x = x, y = y。 color = gender))
scale_colour_discrete(name="Gender"。 breaks=c(0。 1),
labels=c("Male"。 "Female"))
uj5u.com熱心網友回復:
這與在你自己的(第一個)例子中對線使用colour美學和對點使用fill美學有關。在第二個例子中,它是有效的,因為colour美學被用于線和點。
默認情況下,geom_point不能將一個變數映射到fill,因為默認的點形狀(19)沒有填充。
為了使fill在點上作業,你必須在geom_point()中指定shape = 21:25,在aes()之外。
模擬資料
set.seed(4821)
x1 < - rnorm(100。 平均= 5)
set.seed(4821)
x2 < - rnorm(100。 平均= 6)
data <- data. frame(x = rep(seq(20。 80, length. out = 100)。 2),
tc = c(x1。 x2),
性別=因子(c(rep("Female"。 100)。 rep("Male"。 100))))
適合的模型
slrmen < -lm(tc~x I(x^2)。 資料=資料[data["gender"]=="Male"。 ])
slrwomen < -lm(tc~x I(x^2)。 data = data[data[/span>"gender"]=="Female"。 ])
newdat <- data. frame(x = seq(20。 80, length. out = 200))。
fitted.male <- data.frame(x = newdat,
性別 = "Male",
tc = predict(object = slrmen。 newdata = newdat))
fitted.female <- data.frame(x = newdat,
性別 = "Female",
tc = predict(object = slrwomen。 newdata = newdat))
使用colour美學進行繪圖
對點和線都使用colour美學(在ggplot中指定,這樣它就會被整個繼承)。默認情況下,geom_point可以將一個變數映射到colour。
library(ggplot2)
ggplot(data, aes(x = x。 y = tc。 color = gender))
geom_point()
geom_line(data = fitted.male)
geom_line(data = fitted.female)
scale_colour_manual(values = c("tomato"/span>。 "blue")
theme_bw()

使用colour和fill美學進行繪圖
對點使用fill美學,對線使用colour美學(在geom_*中指定美學以防止它們被繼承)。這將會重現這個問題。
ggplot(data。 aes(x = x, y = tc))
geom_point(aes(fill=) 運算子">=性別))
geom_line(data = fitted. 男性。 aes(顏色=性別))
geom_line(data = fitted. 女性。 aes(顏色=性別))
scale_colour_manual(values = c("tomato"/span>。 "blue")
scale_fill_manual(values = c("tomato"/span>。 "blue")
theme_bw()

為了解決這個問題,將geom_point中的shape引數改為可以填充的點狀形狀(21:25)。
ggplot(data, aes(x = x, y = tc))
geom_point(aes(fill = gender)。 形狀= 21)
geom_line(data = fitted. 男性。 aes(顏色=性別))
geom_line(data = fitted. 女性。 aes(顏色=性別))
scale_colour_manual(values = c("tomato"/span>。 "blue")
scale_fill_manual(values = c("tomato"/span>。 "blue")
theme_bw()

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/330203.html
標籤:


