简体   繁体   English

R-基线不从零开始的ggplot条形图

[英]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. 我正在使用ggplot2中的geom_bar在躲避的条形图中绘制8种条件的均值。 My y axis goes from -200 to 1000. Two of the 8 conditions have negative values, the remainder have positive values. 我的y轴从-200到1000。8个条件中的两个具有负值,其余条件具有正值。 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). 当前正值的柱线从0开始。我希望所有柱线都从-200开始(即从-200填充到它们各自的值)。 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) x有8个均值(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..). 我希望每个小节都从-200填充到其平均值(-200到4,-200到423等)。 At the moment the bars are filled from 0 to their mean. 目前,柱状图从0填充到其均值。 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. 对于基线为-200(而不是零)的条形图,可以将y值加200,然后重新标记y轴,以使标签比“默认”标签少200。 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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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