Dima Sukhorukov
Dima Sukhorukov

Reputation: 139

Bar and stacked bars on one plot in ggplot2

Good evening, can anybody help with plotting. I have some data like this:

    DF <- data.frame(
        country_dest=c("Russia", "Germany", "Ukraine" ,"Kazakhstan", 
        "United States", "Italy", "Israel", "Belarus"),
        SumTotal=c(7076562,2509617,1032325,680137,540630,359030,229186,217623)
    )

It is not a big deal to plot it with separate 8 bars, but i am wondering to know is it possible to make a plot with 3 bars, where first bar will be with data of Russia (for example) second will be stacked bar of Germany, Ucraine, Kazakhstan, US and Italy maybe with some legend to understand who is who and third stacked bar of Belarus and Israel.

In internet I have found a solution to create new DF with 0 values, but didn't quite understand.

Than you in advance!

Upvotes: 0

Views: 81

Answers (1)

MrFlick
MrFlick

Reputation: 206606

Well, you will need to add grouping information to your data. Then it becomes straightforward. Here's one strategy

#define groups
grp <-c("Russia"=1, "Germany"=2, "Ukraine"=2,"Kazakhstan"=2, 
        "United States"=2, "Italy"=2, "Israel"=3, "Belarus"=3)
DF$grp<-grp[as.character(DF$country_dest)]

#ensure plotting order
DF$country_dest <- factor(DF$country_dest, levels=DF$country_dest)

#draw plot
ggplot(DF, aes(x=grp, y=SumTotal, fill=country_dest)) + 
    geom_bar(stat="identity")

This will give you

enter image description here

You might wish to give your groups a more descriptive label.

Upvotes: 3

Related Questions