线条图组 [英] Line charts by group
问题描述
我有以下数据,我想创建一个有条件的线图,条件是 group1
和 group2
变量。
dat < - 结构(list(group1)= structure(c(1L,1L,1L,1L,2L,2L,2L ),
.Label = c(a,b),
class =factor),
group2 = c(1L,2L,3L,4L,1L,2L ,3L),
val1 = c(10L,3L,2L,7L,10L,3L,2L),
val2 = c(8L,4L,8L,5L,8L,4L,8L),
val3 = c(7L,5L,6L,9L,7L,5L,6L)),
.Names = c(group1,group2,val1,val2 val3),
class =data.frame,row.names = c(NA,-7L))
理想情况下,我想有两张基于 group1
的图(两个用于 a
和 b
)以及每个组中
1变量我需要基于t的折线图他行变量(基本上连接三个点为 val1
, val2
和 val3 $对于不同的
group2
变量,使用不同的颜色来创建c $ c>)。 >你的意思是这样的:
dat2 < - with(dat,data.frame(group1 = rep(group1,每个= 3),
group2 =因子(rep(group2,each = 3)),
values = stack(dat [,3:5])[,1]))
上面的代码将数据重构为更容易与ggplot一起使用的格式。 dat
是使用添加到您的Q中的 dput()
代码定义的。我认为您想要的图可以生成通过
p < - ggplot(dat2,aes(x = 1:3,y = values,color = group2)) + geom_line()+
geom_point()+ facet_wrap(〜group1,ncol = 2)
p
给出
我基本上不得不补充一些 x
数据,否则你怎么知道x - 这些点应该位于哪个y坐标空间?
I have the following data and I want to create a line chart conditional on group1
and group2
variable.
dat <- structure(list(group1 = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L),
.Label = c("a", "b"),
class = "factor"),
group2 = c(1L, 2L, 3L, 4L, 1L, 2L, 3L),
val1 = c(10L, 3L, 2L, 7L, 10L, 3L, 2L),
val2 = c(8L, 4L, 8L, 5L, 8L, 4L, 8L),
val3 = c(7L, 5L, 6L, 9L, 7L, 5L, 6L)),
.Names = c("group1", "group2", "val1", "val2", "val3"),
class = "data.frame", row.names = c(NA, -7L))
Ideally, I want to have two graphs based on group1
(two for levels a
and b
) and within each group
1 variable I need line charts based on the row variables(basically connecting three points for val1
, val2
, and val3
) with different colors for different group2
variables.
Do you mean something like this:
dat2 <- with(dat, data.frame(group1 = rep(group1, each = 3),
group2 = factor(rep(group2, each = 3)),
values = stack(dat[,3:5])[,1]))
The above code restructures the data into a format more easily used with ggplot. dat
was defined using the dput()
code I added to your Q. The plot I think you want can be produced via
p <- ggplot(dat2, aes(x = 1:3, y = values, colour = group2)) + geom_line() +
geom_point() + facet_wrap(~ group1, ncol = 2)
p
which gives
I've basically had to make up some x
data otherwise how do you know where in the x- and y-coordinate space the points should be located?
这篇关于线条图组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!