Home > OS >  dotplot in ggplot with vertical and horizontal categories
dotplot in ggplot with vertical and horizontal categories

Time:10-15

I'm trying to make a dotplot in ggplot2 with categories on both the vertical and horizontal axes similar to this image:

enter image description here

Below, you can find my try at implementing this through ggplot2:

# load libraries
library(ggplot2)
library(reshape2)

# create toy data frame
df <- data.frame(type=c("A","B","C","D"),
                  trait1=c(1,1,0,0),
                  trait2=c(1,0,1,0))

# convert data to long format 
melt_df <- melt(df)

# my try at dotplot
ggplot(melt_df, aes(x=type, y=value, group=variable))  
  geom_dotplot(binaxis='y', stackdir='center')  
  scale_x_discrete(position = "top")  
  coord_flip()

Could you kindly help me better replicate the image above using the toy dataset that I provided?

CodePudding user response:

You can use plain old geom_point for presence/absence:

ggplot(melt_df, aes(x = variable, y = type, color = factor(value)))  
  geom_tile(fill = 'white', color = 'black', size = 1)  
  geom_point(size =  10)  
  scale_y_discrete(limits = c('D', 'C', 'B', 'A'), expand = c(0, 0))  
  scale_color_manual(values = c('white', 'black'), guide = 'none')  
  scale_x_discrete(position = 'top', expand = c(0, 0), name = 'Trait')  
  theme_minimal(base_size = 16)  
  theme(axis.title.y.left = element_text(angle = 0, vjust = 0.5))

enter image description here

  • Related