简体   繁体   中英

How to plot with ggplot2 a geom_bar graph with color fillings from a data.frame

I would like to get a bar graph in which the bar height corresponds to a total value, and the bar itself is divided into colors according to partial values.

df <- data.frame(name = c("a", "b", "c"), 
                 total = c(10, 20, 30), 
                 left = c(5, 10, 5), 
                 middle = c(4, 5, 15), 
                 right = c(1, 5, 10))

df <- gather(df, key, value, 3:5)

ggplot(df, aes(x = name, y = total, fill = key)) + geom_bar(stat = "identity")

What I get does not respect the distribution of the partial values...

Change total to value in the ggplot:

ggplot(df, aes(x = name, y = value, fill = key)) + geom_bar(stat = "identity")

instead of:

ggplot(df, aes(x = name, y = total, fill = key)) + geom_bar(stat = "identity")

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