问题描述
我正在使用ggplot2中的geom_bar在躲避的条形图中绘制8种条件的平均值.我的y轴从-200到1000.8个条件中的两个条件为负值,其余条件为正值.目前,正值的柱线从0开始.我希望所有柱线都从-200开始(即,从-200填充到它们各自的值).有一个简单的方法可以做到这一点吗?
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 (i.e. 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有8个均值(4,423,-57,724,14,556,37,614)
x has 8 means (4, 423, -57, 724, 14, 556, 37, 614)
我希望每个小节都从-200填充到其平均值(-200到4,-200到423,依此类推.).此刻,柱状图从0填充到其均值.我该如何更改?
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?
谢谢
推荐答案
对于基线为-200(而不是零)的条形图,可以将y值加200,然后重新标记y轴,以使标签为比默认"标签少200.您尚未提供示例数据,所以请告诉我们这是否与您要找的不完全一样.
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)
这篇关于R-基线不从零开始的ggplot条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!