简体   繁体   中英

Stacked bar plot in R with the positive and negative values

I would like to plot a stacked bar plot in R and my data looks as such:

在此处输入图片说明

This table is the values against date and as it can be seen, there are repetitive dates with different sides. I would like to plot a bar plot using this data.

combined = rbind(x,y)
combined = combined[order(combined$Group.1),]
barplot(combined$x,main=paste("x vs y Breakdown",Sys.time()),names.arg = combined$Group.1,horiz = TRUE,las=2,xlim=c(-30,30),col = 'blue',beside = True)

在此处输入图片说明

Want a stacked plot where I can see the values against dates. How do change my code?

You can easily create this figure with ggplot2 . Here a piece of code for you using a data frame similar to what you have:

library(ggplot2)

my_data <- data.frame(
  date = factor(c(1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 8, 8)),
  x = c(-2, 14, -8, -13, 3, -4, 9, 8, 3, -4, 8, -1)
)

g <- ggplot(my_data, aes(x = date, y = x)) +
  geom_bar(
    stat = "identity", position = position_stack(),
    color = "white", fill = "lightblue"
  ) +
  coord_flip()

This is the output:

在此处输入图片说明

Obviously, the official documentation is a good way to start to understand a bit better how to improve it.

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