facet_grid背对背直方图失败 [英] facet_grid of back to back histogram failing
问题描述
I am having some trouble creating a facet grid of a back-to-back histogram created with ggplot.
# create data frame with latency values
latc_sorted <- data.frame(
subject=c(1,1,1,1,1,2,2,2,2,2),
grp=c("K_N","K_I","K_N","K_I","K_N","K_I","K_N","K_I","K_N","K_I"),
lat=c(22,45,18,55,94,11,67,22,64,44)
)
# subset and order data
x.sub_ki<-subset(latc_sorted, grp=="K_I")
x.sub_kn<-subset(latc_sorted, grp=="K_N")
x.sub_k<-rbind(x.sub_ki,x.sub_kn)
x=x.sub_ki$lat
y=x.sub_kn$lat
nm<-list("x","y")
# make absolute values on x axis
my.abs<-function(x){abs(x)}
# plot back-to-back histogram
hist_K<-qplot(x, geom="histogram", fill="inverted", binwidth=20) +
geom_histogram(data=data.frame(x=y), aes(fill="non-inverted", y=-..count..),
binwidth= 20) + scale_y_continuous(formatter='my.abs') + coord_flip() +
scale_fill_hue("variable")
hist_K
这种情况很好,但如果我尝试以下我得到错误:
错误:铸造公式包含未在熔融数据中找到的变量:x.sub_k $ subject
this plots fine but if I try the following I get the error: Error: Casting formula contains variables not found in molten data: x.sub_k$subject
hist_K_sub<-qplot(x, geom="histogram", fill="inverted", binwidth=20) +
geom_histogram(data=data.frame(x=y), aes(fill="non-inverted", y=-..count..),
binwidth= 20) + scale_y_continuous(formatter='my.abs') + coord_flip() +
scale_fill_hue("variable")+
facet_grid(x.sub_k$subject ~ .)
hist_K_sub
任何想法是什么导致这个失败?
any ideas what is causing this to fail?
推荐答案
问题在于 facet_grid
在传递给各层的data.frames中查找。您已创建(隐式和显式)仅具有 lat
数据并且没有主题
信息的data.frames 。如果您使用 x.sub_ki
和 x.sub_kn
,它们确实具有主题
与 lat
值关联的变量。
The problem is that the variables referenced in facet_grid
are looked for in the data.frames that are passed to the various layers. You have created (implicitly and explicitly) data.frames which have only the lat
data and do not have the subject
information. If you use x.sub_ki
and x.sub_kn
instead, they do have the subject
variable associated with the lat
values.
hist_K_sub <-
ggplot() +
geom_histogram(data=x.sub_ki, aes(x=lat, fill="inverted", y= ..count..), binwidth=20) +
geom_histogram(data=x.sub_kn, aes(x=lat, fill="not inverted", y=-..count..), binwidth=20) +
facet_grid(subject ~ .) +
scale_y_continuous(formatter="my.abs") +
scale_fill_hue("variable") +
coord_flip()
hist_K_sub
我也从qplot转换为完整的ggplot语法;这表明ki和kn的平行结构更好。
I also converted from qplot to full ggplot syntax; that shows the parallel structure of ki and kn better.
这篇关于facet_grid背对背直方图失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!