如果我有三组数据:
a1= rnorm(10)
a2= rnorm(10)
a3= rnorm(10)
Run Code Online (Sandbox Code Playgroud)
而不是使用以下方式并排查看:
par(mfrow=c(1,3))
plot(a1)
plot(a2)
plot(a3)
Run Code Online (Sandbox Code Playgroud)
如何在同一个图上获得所有这些点?
csg*_*pie 26
只需使用该points功能:
plot(a1)
points(a2, col=2)
points(a3, col=3)
Run Code Online (Sandbox Code Playgroud)
这相当于:
plot(1:length(a1), a1)
points(1:length(a2), a2, col=2)
points(1:length(a3), a3, col=3)
Run Code Online (Sandbox Code Playgroud)
如果向量具有不相等的长度,则应指定x轴限制:
plot(a1, xlim=c(1, max(length(a1), length(a2), length(a3))))
Run Code Online (Sandbox Code Playgroud)
# 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)
Run Code Online (Sandbox Code Playgroud)
当a1和a3大小相等,这是不可能投入同一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()
Run Code Online (Sandbox Code Playgroud)
