P A S T R Y
P A S T R Y

Reputation: 351

Transform a ggplot stacked bar into pie chart or alternative

I am having trouble deciding how to graph the data I have. It consists of overlapping quantities that represent a population, hence my decision to use a stacked bar.

These represent six population divisions ("groups") wherein group 1 and group 2 are the main division. Groups 4 to 6 are subgroups of two, and these are subgroups of each other. Its simple diagram is below:

Note: groups 1 and 2 complete the entire population or group 1 + group 2 = 100%.

enter image description here

I want all of these information in one chart which I do not know what and how to implement.

So far I have the one below, which is wrong because Group 1 is included in the main bar.

require(ggplot2)
require(reshape)

tab <- data.frame(
  set=c("XXX","XXX","XXX","XXX","XXX","XXX"),
  group=c("1","6","5","4","3","2"),
  rate=as.numeric(c(10000,20000,50000,55000,75000,100000))
)

dat <- melt(tab)
dat$time <- factor(dat$group,levels=dat$group)

ggplot(dat,aes(x=set)) +
  geom_bar(aes(weight=value,fill=group),position="fill",color="#7F7F7F") +
  scale_fill_brewer("Groups", palette="OrRd")

enter image description here

What do you guys suggest to visualize it? I want to use R and ggplot for consistency and uniformity with the other graphs I have made already.

Upvotes: 3

Views: 1272

Answers (2)

shahram
shahram

Reputation: 41

My guess is what you need is a treemap. Please correct me if I misunderstood your question. here a link on Treemapping]1

If tree map is what you need you can use either portfolio package or googleVis.

Upvotes: 0

topchef
topchef

Reputation: 19823

Using facets you can divide your plot into two:

# changed value of set for group 1
tab <- data.frame(
  set=c("UUU","XXX","XXX","XXX","XXX","XXX"),
  group=c("1","6","5","4","3","2"),
  rate=as.numeric(c(10000,20000,50000,55000,75000,100000))
)

# explicitly defined id.vars
dat <- melt(tab, id.vars=c('set','group'))
dat$time <- factor(dat$group,levels=dat$group)

# added facet_wrap, in geom_bar aes changed weight to y, 
# added stat="identity", changed position="stack"
ggplot(dat,aes(x=set)) +
  geom_bar(aes(y=value,fill=group),position="stack", stat="identity", color="#7F7F7F") +
  scale_fill_brewer("Groups", palette="OrRd") +
  facet_wrap(~set, scale="free_x")

visual with facet and changes

Upvotes: 1

Related Questions