绘制具有不同形状的子集

时间:2018-02-14 14:58:09

标签: r ggplot2

快速问题:我有一个数据集,我随机分为训练和测试子集。然后我做了一些统计分析,想在同一个图中一起绘制结果,但是为两个不同的子集使用不同的形状。

我是ggplot的新手,所以我的问题是必须在开头为ggplot提供完整的数据集。由于我通过随机索引将数据分成两组,因此无法为aes找到正确的选择属性()

data=read.csv("...",sep=" ")
data$class = as.factor(data$class - 1)
colnames(data)=c("y","x1","x2")
n = dim(data)[1]
order = sample(n)
test = data[order[1:(n/2)],]
train = data[order[(n/2):n,]
#...
ggplot(train) + geom_point( aes(x =x1, y = x2, color = y)) 
# this should be done for the whole dataset, kinda like this
# ggplot(data) + geom_point(aes(x=x1, y=x2, color=y, shape=(index is in test and not train)))
# which is obviously not valid

谢谢你的时间, 尼古拉斯

2 个答案:

答案 0 :(得分:0)

如果我们假设数据集具有相同的列:

# Loading data    
data <- structure(list(y = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor"), x1 = c(15.6, 11.2, 18.6, 16.8, 21, 15.2, 14.6, 17.6, 14, 16), x2 = c(5.64, 4.38, 5.68, 7.8, 4.32, 6.75, 5.25, 5.05, 5.2, 7.22)), .Names = c("y", "x1", "x2"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), class = "data.frame")
n = dim(data)[1]
order = sample(n)
test = data[order[1:(n/2)],]
train = data[order[(n/2):n,]

test$identifier <- as.factor(1) # mark the test with 1
train$identifier <- as.factor(0) # mark the train with 0

df_out <- rbind(test,train) # combine the dataframes

ggplot(df_out,aes(x = x1,y = x2,color = y, shape = identifier)) + geom_point() # plot the new df

这会产生:

Graph with different shapes based on dataset

答案 1 :(得分:0)

如果您的示例中有2个数据集,则这是另一种方法

library(ggplot2)
data = structure(list(y = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor"), x1 = c(15.6, 11.2, 18.6, 16.8, 21, 15.2, 14.6, 17.6, 14, 16), x2 = c(5.64, 4.38, 5.68, 7.8, 4.32, 6.75, 5.25, 5.05, 5.2, 7.22)), .Names = c("y", "x1", "x2"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"), class = "data.frame")
data = data.frame(data)
n = dim(data)[1]
order = sample(n)
test = data[order[1:(n/2)],]
train = data[order[(n/2):n],]

ggplot(test)+geom_point(aes(y = x1,x=x2))+
  geom_point(data = train, aes(y = x1,x = x2), pch = 10, col = "dargreen")