簡體   English   中英

如何在R中疊加散點圖?

[英]How to overlay scatterplots in R?

如果我有三組數據:

a1= rnorm(10)
a2= rnorm(10)
a3= rnorm(10)

而不是使用以下方式並排查看:

par(mfrow=c(1,3))
plot(a1)
plot(a2)
plot(a3)

如何在同一個圖上獲得所有這些點?

只需使用points功能:

plot(a1)
points(a2, col=2)
points(a3, col=3)

這相當於:

plot(1:length(a1), a1)
points(1:length(a2), a2, col=2)
points(1:length(a3), a3, col=3)

如果向量具有不相等的長度,則應指定x軸限制:

plot(a1, xlim=c(1, max(length(a1), length(a2), length(a3))))
# To overlay scatterplots in R

# import the required libraries
library(ggplot2)
library(reshape2)

# assign data
a1=rnorm(10)
a2=rnorm(10)
a3=rnorm(10)

# create a dataframe from combined data
# and set count to however many points are in each dataset
df = data.frame(a1, a2, a3, count = c(1:10))

# melt the dataframe
df.m = melt(df, id.vars ="count", measure.vars = c("a1","a2","a3"))

# take a look at what melt() does to get an idea of what is going on
df.m

# plot out the melted dataframe using ggplot
ggplot(df.m, aes(count, value, colour = variable)) + geom_point() + ylim(-3,3)

# swapping the axis
ggplot(df.m, aes(value, count, colour = variable)) + geom_point() + xlim(-3,3)

a1a3的大小相等時,不可能將相同的data.frame作為列放入,作為melt輸入。 解決方案是簡單地使用一個list

a1 = rnorm(10)
a2 = rnorm(25)
a3 = rnorm(17)
a_list = list(a1, a2, a3)
a_df = do.call("rbind", lapply(a_list, 
                                function(x) data.frame(value = x, 
                                                       count = seq_along(x))))
ID_options = LETTERS[seq_along(a_list)]
a_df$ID = rep(ID_options, sapply(a_list, length))
ggplot(a_df, aes(x = value, y = count, color = ID)) + geom_point()

在此輸入圖像描述

要為答案添加多樣性,您還可以使用lattice 這里,每組代碼樣本中的第二行表示交換軸。

library(lattice)

## If you have already created the "df" 
##   data.frame from your example
xyplot(count ~ a1 + a2 + a3, data=df)
xyplot(a1 + a2 + a3 ~ count, data=df)

## Without first creating the "df" 
##   data.frame from your example    
xyplot(1:10 ~ a1 + a2 + a3)
xyplot(a1 + a2 + a3 ~ 1:10)

如果你正在使用不等長度的向量,你可以從我分享的關於cbind ing不等長度向量的答案加載函數,然后使用我提到的第一種方法。 更新 :有關此功能的最新版本,請參閱https://gist.github.com/mrdwab/6789277

例:

a1 = rnorm(10)
a2 = rnorm(25)
a3 = rnorm(17)

library(lattice)
library(devtools)
## source_gist is not working properly unless you provide 
##   the full URL to the "raw" file
source_gist("https://gist.github.com/mrdwab/6789277/raw/9bd7d5931389ec475c49c1918d26d9899796a5d0/Cbind.R")

newdf <- Cbind(a1, a2, a3)
xyplot(a1 + a2 + a3 ~ sequence(nrow(newdf)), data=newdf)
xyplot(sequence(nrow(newdf)) ~ a1 + a2 + a3, data=newdf)

這是一個示例圖,對默認顏色進行了一些調整:

xyplot(sequence(nrow(newdf)) ~ a1 + a2 + a3, data=newdf, 
       pch = 21, fill = c("black", "red", "green"), cex = 1)

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM