How to visualize the group and subgroup frequency?

Viewed 1042

I have to plot the frequency data using a group variable As and subgroup variable ADs. What is the best way to visualize the frequency ie., pie chart or mosaic? Is there any function available in ggplot2?

df <- data.frame(As=c('GeA','GeA','GeA', 'GA'), 
             ADs=c('A44','A33','A37','A141'),
             freq=c(501,65,50,103))

#    As  ADs freq
# 1 GeA  A44  501
# 2 GeA  A33   65
# 3 GeA  A37   50
# 4  GA A141  103

Some thoughts are like below:

image1

However, is there any way to differentiate both group and subgroup in a single plot?

Out of the proposed solutions, below two charts looked promising.

Pie Chart & Tile Graph

piecharttileGraph

I have used the following code suggested by M--.

df.2 <- df
df.2$ymax <- with(df.2, ave(freq, As, FUN=cumsum))
df.2$ymin <- lag(df.2$ymax, default = 0)
df.2$ymin <- ifelse(lag(as.character(df.2$As), default = 0) != df.2$As, 0, df.2$ymin)

df.legend <- df.2[with(df.2, order(As)), ]

library(ggplot2)
# Pie Chart
ggplot(df.2) + 
  geom_rect(aes(fill=As, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
  geom_rect(aes(fill=ADs, ymax=ymax, ymin=ymin, xmax=3, xmin=0)) +
  xlim(c(0, 4)) + 
  theme(aspect.ratio=1) +
  coord_polar(theta="y") +
  scale_x_continuous(breaks=c(0,3), labels=c("ADs", "As")) + 
  annotate("text", x=rep(1.5,4), y=c(50, 350,530,590), 
           label= as.character(df.legend$ADs)) + 
  annotate("text", x=rep(3.5,2), y=c(50, 350), 
           label= as.character(unique(df.legend$As))) + 
  theme(legend.position="none", axis.title.x=element_blank(),
        axis.title.y=element_blank())

# Tile Graph
ggplot(df.2) + 
  geom_rect(aes(fill=As, ymax=ymax, ymin=ymin, xmax=4, xmin=3)) +
  geom_rect(aes(fill=ADs, ymax=ymax, ymin=ymin, xmax=3, xmin=0)) +
  xlim(c(0, 4)) + theme(aspect.ratio=1) +
  scale_x_continuous(breaks=c(1.5,3.5), labels=c("ADs", "As")) + 
  annotate("text", x=rep(1.5,4), y=c(50, 350,530,590), 
           label= paste(as.character(df.legend$ADs), df.legend$freq,sep= " = ")) + 
  annotate("text", x=rep(3.5,2), y=c(50, 350), 
           label= as.character(unique(df.legend$As))) + 
  theme(legend.position="none", axis.title.x=element_blank(),
        axis.title.y=element_blank())

However, I didn't get the same output

Pie Chart & Tile Graph

piechart_err tileGraph_err

Message: Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.

Could you please advise what would be the issue? Is there any difference in the version of the package(s) used?

1 Answers
Related