R - ggplot2通过过滤,垂直堆叠的不同列

时间:2016-10-01 09:50:38

标签: r plot ggplot2 facet one-hot-encoding

我有一个数据框(df2),其中包含Age,Info,Target以及Info转换为单热编码列,如下所示。

library(qdapTools)
require(reshape)

mydf <- structure(list(Age = c(99L, 10L, 40L, 15L),
                       Info = c("good, bad, sad", "nice, good, happy, joy", "NULL", "okay, nice, good, wild, go"),
                       Target = c("Boy", "Girl", "Boy", "Boy")), 
                  .Names = c("Age", "Info", "Target"),
                  row.names = c(NA, 4L),
                  class = "data.frame")

df_with_ohe <- cbind(mydf, mtabulate(strsplit(mydf$Info, ", ")))

mydf
df_with_ohe

added_cols = names(df_with_ohe)[length(names(mydf))+1:length(names(df_with_ohe))]

 [1] "bad"   "go"    "good"  "happy" "joy"   "nice"  "NULL"  "okay"  "sad"   "wild"

这是df2

  Age                       Info Target bad go good happy joy nice NULL okay sad wild
1  99             good, bad, sad    Boy   1  0    1     0   0    0    0    0   1    0
2  10     nice, good, happy, joy   Girl   0  0    1     1   1    1    0    0   0    0
3  40                       NULL    Boy   0  0    0     0   0    0    1    0   0    0
4  15 okay, nice, good, wild, go    Boy   0  1    1     0   0    1    0    1   0    1

我想绘制不同信息类型的年龄分布,即&#34; good&#34;,&#34; bad&#34;等等。例如:

# considering on "good" column

df = subset(df_with_ohe, df_with_ohe[,"good"] == 1)

ggplot(df, aes(Target, Age)) + geom_boxplot()

Distribution of Age versus "Good" column

如何在单个图中使用One-Hot-Encoded功能对所有added_cols列进行此类绘图?也许使用Facet?

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

df <- do.call(rbind, apply(mydf, 1, function(x) cbind.data.frame(Age=x[1], 
                                  Type=unlist(strsplit(x[2], split=', ')), 
                                  Target=x[3])))
df$Age <- as.integer(as.character(df$Age))
ggplot(df, aes(Target, Age)) + 
   geom_boxplot() + 
   facet_wrap(~Type, scales = 'free')

enter image description here