這是一些帶有x和y值的資料,以及兩個分組變數level1和level2。我想用colour和linetype美學來繪制分組變數,如下所示:
library(ggplot2)
library(dplyr)
set.seed(100)
dat <- data.frame(
x = rep(2010:2014, each = 6),
level1 = rep(letters[1:3], times = 10),
level2 = rep(rep(c("y", "z"), each = 3), times = 5),
y = rnorm(30)
)
dat %>%
ggplot(aes(x = x, y = y, colour = level1, linetype = level2))
geom_line()

這個情節其實是對的。問題是當我將 x 軸更改為一個因子(或字符)時:
dat %>%
mutate(x = factor(x)) %>%
ggplot(aes(x = x, y = y, colour = level1, linetype = level2))
geom_line()
geom_path:每組僅包含一個觀察值。需要調整群體審美嗎?
這似乎很公平,我從未真正指定美學,它似乎只是在數字group時開箱即用。x我的第一個想法是指定group = level1,但這會導致
錯誤:geom_path:如果您使用點線或虛線,顏色、大小和線型必須在整個線上保持不變
Which also seems reasonable, because there are actually six lines, and they're defined by the combination of level1 and level2, not just level1. But I'm not sure it's possible to specify a multi-level line grouping, e.g.,
dat %>%
mutate(x = factor(x)) %>%
ggplot(aes(x = x, y = y, colour = level1, linetype = level2))
geom_line(aes(group = c(level1, level2)))
Error: Aesthetics must be either length 1 or the same as the data (30): group
The desired output is a reproduction of the first plot, but with the x-variable as a factor rather than numeric. Any insight into why the plot seems to work when x is numeric would be interesting as well. Thanks.
uj5u.com熱心網友回復:
嘗試使用兩個分組變數通常是正確的想法。為此,您需要使用group 引數之間level1和中的互動。level2
library(ggplot2)
library(dplyr)
dat %>%
mutate(x = factor(x)) %>%
ggplot(aes(x = x, y = y, colour = level1, linetype = level2, group = interaction(level1, level2)))
geom_line()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440259.html
