ggplot2:将barplot(geom_bar)的基线移至最小数据值 [英] ggplot2: Shift the baseline of barplot (geom_bar) to the minimum data value

查看:57
本文介绍了ggplot2:将barplot(geom_bar)的基线移至最小数据值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 geom_bar 生成条形图.我的条形既有负值又有正值:

I'm trying to generate a bar plot using geom_bar. My bars have both negative and positive values:

set.seed(1)
df <- data.frame(y=log(c(runif(6,0,1),runif(6,1,10))),se=runif(12,0.05,0.1),name=factor(rep(c("a","a","b","b","c","c"),2),levels=c("a","b","c")),side=factor(rep(1:2,6),levels=1:2),group=factor(c(rep("x",6),rep("y",6)),levels=c("x","y")),stringsAsFactors=F)

此plot命令绘制正条朝上,负条朝下:

This plot command plots the positive bars to face up and the negative ones to face down:

library(ggplot2)
dodge <- position_dodge(width=0.9)
limits <- aes(ymax=y+se,ymin=y-se)
ggplot(df,aes(x=name,y=y,group=interaction(side,name),col=group,fill=group))+facet_wrap(~group)+geom_bar(width=0.6,position=position_dodge(width=1),stat="identity")+
geom_bar(position=dodge,stat="identity")+geom_errorbar(limits,position=dodge,width=0.25)

我的问题是如何将基线设置为所有条形的最小值而不是0,并且使红色条形朝上?

My question is how do I set the base line to the minimum of all bars instead of at 0 and therefre have the red bars facing up?

推荐答案

此简单的技巧也适用:

m <- min(df$y) # find min
df$y <- df$y - m
ggplot(df,aes(x=name,y=y,group=interaction(side,name),col=group,fill=group))+
  facet_wrap(~group)+
  geom_bar(width=0.6,position=position_dodge(width=1),stat="identity")+
  geom_bar(position=dodge,stat="identity")+
  geom_errorbar(limits,position=dodge,width=0.25) +
  scale_y_continuous(breaks=seq(min(df$y), max(df$y), length=5),labels=as.character(round(seq(m, max(df$y+m), length=5),2))) # relabel

这篇关于ggplot2:将barplot(geom_bar)的基线移至最小数据值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆