我的一个朋友帮助我创建了一个使用基本绘图功能生成散点图的代码。现在我想用ggplot制作同样的图,但是我不知道/不明白如何在相应的ggplot选项中转换基本绘图函数的cex参数。
这是我的数据示例
df=read.table(text="
A B C D E F G H I J
1 2 3 4 5 1 2 3 4 5
2 3 4 5 6 2 3 4 5 6
3 4 5 6 7 3 4 5 6 7
4 5 6 7 8 4 5 6 7 8
5 6 7 8 9 5 6 7 8 9
6 7 8 9 10 6 7 8 9 10
7 8 9 10 11 7 8 9 10 11
8 9 10 11 12 8 9 10 11 12
9 10 11 12 13 9 10 11 12 13",header=T)这是我用于基本plot函数的代码
temp <- as.matrix(df)
x <- ncol(temp)/2
y <- nrow(temp)
maxtemp <- max(temp [ , 1:x], na.rm = T)
plot(rep(1, y) ~ temp [, x + 1], type = "p", pch = 1, cex = 5*temp [, 1]/maxtemp , xlim = c(0, 15), ylim = c(0,6))
for(i in 1:(x-1)){
points(rep(1 + i, y) ~ temp [, x + 1 + i], type = "p", pch = 1, cex = 5*temp [, 1 + i]/maxtemp)
next}为了在ggplot中绘制相同的图,我写了这段代码,但是我没有得到相同的图片,点的大小不一样,我猜这是因为plot使用cex,而ggplot使用大小,我不知道如何处理这个问题……
temp <- data.table(df)
colnames(temp) <- c(paste("I",c(1:5), sep=""), c(1:5))
x <- ncol(temp)/2
maxtemp <- max(temp [ , 1:x], na.rm = T)
for(t in 1:5){
temp[, t] <- 5*temp[, t, with = FALSE]/maxtemp
next}
#I do this to create the 'cex' values, as cex does not exist in ggplot
ggplot(gather(temp[, 6:10]),aes(x = value, y = as.numeric(key))) + geom_point(aes(size = gather(temp[, 1:5])$value), shape = 1) + xlim(0, 15) + ylim(0, 6) + theme_bw() + theme(legend.position = "none", panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + xlab("") + ylab("")我做错了什么?
发布于 2017-05-23 15:19:18
好了,我想我找到了一种方法来做我想做的事情。我正在寻找别的东西,我在ggplot2的参考手册中偶然发现了下面这句话
# To set aesthetics, wrap in I()
qplot(mpg, wt, data = mtcars, colour = I("red"))所以我试了一试,几次尝试之后,我得到了以下代码
ggplot(gather(temp[, 6:10]),aes(x = value, y = as.numeric(key))) + geom_point(aes(size = I(gather(temp[, 1:5])$value*2)), shape = 1) + xlim(0, 15) + ylim(0, 6) + theme_bw() + theme(legend.position = "none", panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + xlab("") + ylab("")使用aes(size = I(gather(temp[, 1:5])$value*2))时,我得到的绘图与使用plot()函数(第一段代码)几乎完全相同。我不完全理解cex和aes(I())之间的关系,但它做了我想要的。也许有人可以对此发表评论。
https://stackoverflow.com/questions/44113351
复制相似问题