我的分组数据如下:
group x y
group1 0 5
group4 0 5
group1 7 5
group4 0 5
group5 7 5
group1 7 5
group1 0 6
group2 0 6
group4 0 5
group2 0 5
group3 7 5
x和y都是离散值,范围在0到7之间。我想得到一个图,根据各自的x和y值将每个组数据放在xy平面上。例如,我可以有多个group1点,所有这些都应该共享相同的颜色。如何在R?
中做到这一点答案 0 :(得分:4)
数据:
dat <- read.table(text = "group x y
group1 0 5
group4 0 5
group1 7 5
group4 0 5
group5 7 5
group1 7 5
group1 0 6
group2 0 6
group4 0 5
group2 0 5
group3 7 5", header = TRUE)
您可以使用优秀的ggplot2
包进行简单的绘图:
library(ggplot2)
ggplot(dat, aes(x = x, y = y, colour = group)) +
geom_point() +
facet_wrap( ~ group)
在这里,我使用facet_wrap
为每个组创建构面。原则上这不是必需的,因为组的点可以通过它们的颜色来区分。但在这种情况下,图中只有三个不同的位置。因此,如果数据是在单个散点图中绘制的,那么并非所有点都可见。
答案 1 :(得分:4)
使用Sven的答案中的数据,你也可以看一下格子包,它应该已经安装了你的R装置:
library(lattice)
# Each group in a separate mini plot
xyplot(y ~ x | group, data = dat)
# All groups in one plot, different colors for each group
# Not at all interesting with the example data you've provided
xyplot(y ~ x, groups=dat$group, data = dat)
以下是每个数据的示例:
set.seed(1)
mydf <- data.frame(
group = sample(letters[1:4], 50, replace = TRUE),
x = runif(50, 0, 7),
y = runif(50, 0, 7)
)
xyplot(y ~ x, groups=mydf$group, data = mydf,
auto.key = list(corner = c(0, .98)), cex = 1.5)
xyplot(y ~ x | group, data = mydf,
auto.key = list(corner = c(0, .98)), cex = 1.5)
答案 2 :(得分:0)
dd<- read.table("put the path to the txt file containing the data here", header=TRUE)
g <- ggplot(dd, aes(as.factor(group)))
g <- g + geom_point(aes(y=x), colour="red")
g <- g + geom_point(aes(y=y), colour="green")
g
这将在单个图中为您提供x和y作为组的函数,如下所示。