mattbawn
mattbawn

Reputation: 1378

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. I am new to plotting in R how may I adapt the code?

Upvotes: 0

Views: 484

Answers (1)

Spacedman
Spacedman

Reputation: 94202

If you give your data an id column then you can follow the example in the linked question. Simplified 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 

data grid]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). 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.

Upvotes: 1

Related Questions