简体   繁体   English

在R中将分类数据绘制为镶嵌图

[英]Plot Categorical data as mosaic in R

I have a data structure that can be imagined as this: 我有一个可以想象成这样的数据结构:

 a <- c("P","F","P","P")
 b <- c("P","P","P","P")
 c <- c("P","P","N","P")
 d <- c("P","F","P","F")

 data <- data.frame(a,b,c,d)

I wish to plot the values as blocks of colour. 我希望将这些值绘制成彩色块。 I have seen the same/a similar question here and I would like the same type of ggplot output. 我所看到的相同/相似的问题, 在这里 ,我想同类型的ggplot输出。 I am new to plotting in R how may I adapt the code? 我是R中的新手,我该如何修改代码?

If you give your data an id column then you can follow the example in the linked question. 如果为数据提供一个id列,则可以按照链接的问题中的示例进行操作。 Simplificated somewhat: 有点简化:

data$id=c("e","f","g","h")
ggplot(reshape2::melt(data,id.var="id"), aes(x=id, y=variable, fill=value)) + geom_tile()
# Warning message:
attributes are not identical across measure variables; they will be dropped 

数据网格 ] 1 ] 1

The warning is because your data frame has factors in each column, and each one has different levels (because not every column has all of F, N, and P). 该警告是因为数据框的每一列都有因素,并且每一列都有不同的级别(因为并非每一列都具有F,N和P)。 If you converted to character, or if your real use case constructs it from factors with the complete set of levels, then you won't get a warning. 如果您转换为角色,或者如果您的实际用例是根据具有完整级别集合的因素构建的,则不会收到警告。 Otherwise ignore. 否则忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM