简体   繁体   中英

R - ggplot bar graph with baseline that doesn't start at zero

I am plotting means for 8 conditions in a dodged bar graph using geom_bar in ggplot2. My y axis goes from -200 to 1000. Two of the 8 conditions have negative values, the remainder have positive values. Currently the bars for the positive values start at 0. I would want all the bars to start at -200 (ie be filled from -200 to their respective values). Is there an easy way to achieve this?

graph <-  ggplot(data=data, aes(x, y, fill = z)) + 
      geom_bar(stat="identity", position = "dodge", width = 0.4) +
      scale_y_continuous(limits = c(-200, 1000), breaks =c(-200,0,200,400,600,800,1000), expand = c(0,0))

x has 8 means (4, 423, -57, 724, 14, 556, 37, 614)

I want each of the bars to be filled from -200 to their mean so (-200 to 4, -200 to 423, etc..). At the moment the bars are filled from 0 to their mean. How can I change this?

Thanks

For a bar plot with a baseline of -200 instead of zero, you can add 200 to your y values and then relabel the y axis so that the labels are 200 less than the "default" labels. You haven't provided sample data, so let me know if this isn't exactly what you're looking for.

# Fake data (adapted from @lawyeR)
x <- rep(c("AA", "BB", "CC", "DD"), 2) 
y <- c(4, 423, -57, 724, 14, 556, 37, 614) 
z <- rep(c("A", "B", "C", "D"), 2) 
data <- data.frame(x=factor(x), y=y, z=z) 

library(dplyr)

# Add a grouping variable for dodging multiple bars with the same x value
data = data %>% group_by(x) %>%
  arrange(y) %>%
  mutate(dodgeGroup = 1:n())

ggplot(data=data, aes(x, y + 200, fill = z, group=dodgeGroup)) + 
  geom_bar(stat="identity", position = "dodge", width = 0.5,
           colour="grey20", lwd=0.3) + 
  scale_y_continuous(limits = c(-200,1000), breaks=seq(-200,1000,200),
                     labels=seq(-200,1000,200) - 200)

在此处输入图片说明

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