我正在开展一个项目,我有多个响应变量并希望显示有序的毛虫图。使用基本R绘图功能
相当简单#generate random data frame
set.seed(42)
my_df<-data.frame(x=rnorm(100), y=runif(100,-2,2), z=rpois(100, 10))
#3 panels of plots
par(mfrow=c(1,3))
#note the abline to show an axis at y=0
sapply(c("x", "y", "z"), function(i){ plot(sort(my_df[[i]])); abline(0,0)})
但我不知道如何使用ggplot2来做到这一点。为了将这三个面板放在一起,我知道我必须融合数据框,但是......如何通过变量进行排序并在以后用0轴进行绘图?到目前为止,我所拥有的只是......
melt_df<-melt(my_df)
qplot(1:100, value, data=melt_df, geom="point",facets=~variable)+theme_bw(base_size=16)
答案 0 :(得分:5)
建立关闭jebyrnes的答案 - 您可以将y轴设置为facet_wrap
中的自由比例作为参数。我们可以使用geom_hline()
添加水平线:
ggplot(melt_df, aes(1:100, value)) + geom_point() +
facet_wrap(~ variable, ncol = 3, scales = "free_y") +
geom_hline(aes(intercept = 0), linetype = 2) +
theme_bw(base_size = 16)
您可以使用stat_qq()
获得相同的结果,并避免事先使用ddply
进行排序。不同之处在于我们只需要将sample
参数传递给aes
:
ggplot(melt_df, aes(sample = value)) + geom_point(stat = "qq") +
facet_wrap(~ variable, ncol = 3, scales = "free_y") +
geom_hline(aes(intercept = 0), linetype = 2) +
theme_bw(base_size = 16)
答案 1 :(得分:1)
第1步:订购由ddply完成。
melt_df<-melt(my_df)
melt_df<-ddply(melt_df, .(variable), summarize, value=sort(value))
qplot(1:100, value, data=melt_df, geom="point",facets=~variable)+theme_bw(base_size=16)
轴部分仍然令我感到困惑,特别是考虑到3个方面。
答案 2 :(得分:1)
######## Begin: base R approach ###########
#generate random data frame
set.seed(42)
my_df<-data.frame(x=rnorm(100), y=runif(100,-2,2), z=rpois(100, 10))
#3 panels of plots
par(mfrow=c(1,3))
#note the abline to show an axis at y=0
sapply(c("x", "y", "z"), function(i){ plot(sort(my_df[[i]])); abline(0,0)})
######## End: base R approach ###########
######## Begin: data.table + ggplot2 approach ###########
library(data.table)
library(ggplot2)
melt_df<-melt(my_df)
melt_dt<-melt_df
setDT(melt_dt)
setkey(melt_dt, variable, value)
catey <- ggplot(melt_dt, aes(x=rep(1:100,3), y=value)) + geom_point() +
facet_wrap(~ variable, ncol = 3, scales = "free_y") +
geom_hline(aes(intercept = 0), linetype = 2) +
theme_bw(base_size = 16)
## catepillar:
catey
## with line ranges:
melt_dt[, minvalue:= -2*value+value]
melt_dt[, maxvalue:= 2*value+value]
butterfly <- catey + geom_linerange(aes(ymin=minvalue, ymax=maxvalue))
butterfly
######## End: data.table + ggplot2 approach ###########