[英]How to unify a legend with different types of scales in ggplot?
我有一個由 3 個不同因素分隔的數據框。 我想用散點圖 plot 表示此數據框,對每個因素使用不同類型的比例。
我想使用形狀 21、22 和 24,它們是帶有輪廓和彩色填充的形狀。 但是,圖例中的填充比例顯示不正確。 另外,我想統一圖例,使標簽看起來像這樣(在 MWE 中,我用 1 到 18 的數字表示這些標簽( labels = 1:18
)):
我遵循了這個答案的建議,但是結果 plot 並不像預期的那樣。 有誰知道我該如何解決這個問題?
library(ggplot2)
Factor1 <- c('A', 'B')
Factor2 <- c('M', 'N', 'O')
Factor3 <- c('V1', 'V2', 'V3')
DF <- expand.grid(Factor1 = Factor1,
Factor2 = Factor2,
Factor3 = Factor3)
DF$Result <- runif(n =18,
min = 0,
max = 100)
DF <- DF[order(DF[, "Result"]), ]
DF$Order <- 1:18
ggplot(data = DF,
aes(x = Order,
y = Result,
fill = Factor1,
shape = Factor2,
size = Factor3)) +
geom_point() +
scale_fill_manual(name = "Legend",
values = c('blue', 'red'),
labels = 1:18) +
scale_shape_manual(name = "Legend",
values = c(21,22,24),
labels = 1:18) +
scale_size_manual(name = "Legend",
values = c(2,4,6),
labels = 1:18)
按照您的鏈接將給出正確的結果,但它需要相當多的努力....我為Factor1
和Factor2
做了一個例子。
DF %>%
rowwise %>%
mutate(Fac = paste0(c(Factor1, Factor2), collapse = "-") %>% as.factor) %>%
ggplot( aes(x = Order,
y = Result,
fill = Fac,
shape = Fac,
size = Factor3)) +
geom_point() +
scale_fill_manual(name = "Legend",
values = c('blue', 'red', 'blue', 'red', 'blue', 'red'),
labels = c("A-M", "B-M", "A-N", "B-N", "A-O", "B-O")) +
scale_shape_manual(name = "Legend",
values = c(21,21,22,22,24,24),
labels = c("A-M", "B-M", "A-N", "B-N", "A-O", "B-O")) +
scale_size_manual(name = "Legend",
values = c(2,4,6),
labels = 1:18)
要與Factor3
結合,您可以從
DF %>%
rowwise %>%
mutate(Fac = paste0(c(Factor1, Factor2, Factor3), collapse = "-") %>% as.factor) %>%
ggplot( aes(x = Order,
y = Result,
fill = Fac,
shape = Fac,
size = Fac))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.