简体   繁体   中英

How to create a stacked and grouped bar chart from two data frames?

I have a stacked barchart that looks like this .

If I have a second dataframe that has the same layout as the one that created the plot, and I want to group both datasets by position while still keeping the stacked percentages, how would I go about this. I'm not sure how to do it in ggplot2

Hard to say without seeing the data and without more information about what you actually want to achieve, but the general approach I would use is to say combine your dataframes - especially if the variables are the same. You just want to make sure to maintain "where" each dataset originated, and that will be your identifying column.

So, if your data is in myData1 and myData2 :

# add identifying columns
myData1$id <- 'dataset1'
myData2$id <- 'dataset2'

# put them together
newData <- rbind(myData1, myData2)

You are not clear on what you're looking for in the combined plot, so you can go about that any number of ways (depending on what you want to do). Maybe the simplest example would be to use facet_grid() or facet_wrap() from ggplot2 to show them in side-by-side plots:

ggplot(newData, aes(x=name, y=value)) +
    geom_col(aes(fill=gene)) +
    facet_wrap(~id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM