使用ggplot创建一个以零为中心的堆叠条形图 [英] Creating a stacked bar chart centered on zero using ggplot

查看:138
本文介绍了使用ggplot创建一个以零为中心的堆叠条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用g中的ggplot2来处理堆叠的水平条形图。



这是我的R代码:

  ggplot(results,aes(x = Protocol,y = Time,fill = Phase))+ 
geom_bar(stat =identity)+ coord_flip )

它产生这张图:



我希望居中该图表,以便阶段1和阶段2位于左侧,阶段3和4个在右边。



这是我正在寻找的一个大概的想法。但想象一下,中线是时间0,并且时间在任一方向都变为正值:
p>

我在想我应该让两张图背对背吗?

解决方案

这是我的意思:

  library(scales)
dat < - read.csv(〜/ Downloads /bench.csv\",stringsAsFactors = TRUE)
dat $ Time1< - ifelse(dat $ Phase%in%c('Decode','Deserialize'), - dat $ Time,dat $ Time)

up < - dat [dat $ time1> = 0,]
down <-dat [dat $ Time1< 0,]

commapos< - 函数(x,...){
格式(abs(x),big.mark =,,trim = TRUE,
科学= FALSE,...)
}

ggplot()+
geom_bar(data = up,aes(x = Protocol,y = Time1,fill = as。整数(阶段)),统计=身份)+
geom_bar(data = down,aes(x = Protocol,y = Time1,fill = as.integer(Phase)),stat =identity)+
scale_y_continuous(labels = commapos)+
coord_flip()



<$> commapos formatter我实际上只是从我自己现有的代码中抓起来,当时我做了类似的事情。你可能不想要那种确切的格式,但是 abs(x)是关键部分。



另外,note你的阶段变量是一个字符/因子,所以要从你的原始颜色栏我必须强制回到整数。



而且,正如我所提到的ggplot会当使用小于零的值时,抱怨堆叠没有被很好地定义。如果您尝试这种方式而不将数据框分隔为正值或负值,您将会看到原因。


I'm currently working with a stacked horizontal bar graph chart using ggplot2 in R.

This is my R code:

ggplot(results, aes(x=Protocol, y=Time, fill=Phase)) + 
  geom_bar(stat="identity") + coord_flip()

And it produces this graph:

I want to center this chart so that Phase 1 and 2 are on the left and Phase 3 and 4 are on the right.

Here is a rough idea of what I'm looking for. But imagine the center line is time 0, and time goes positive in either direction:

I'm thinking I should make two graphs back to back?

解决方案

Here's what I mean:

library(scales)
dat <- read.csv("~/Downloads/bench.csv",stringsAsFactors = TRUE)
dat$Time1 <- ifelse(dat$Phase %in% c('Decode','Deserialize'),-dat$Time,dat$Time)

up <- dat[dat$Time1 >= 0,]
down <- dat[dat$Time1 < 0,]

commapos <- function(x, ...) {
    format(abs(x), big.mark = ",", trim = TRUE,
           scientific = FALSE, ...)
}

ggplot() + 
    geom_bar(data = up,aes(x = Protocol,y = Time1,fill = as.integer(Phase)),stat = "identity") + 
    geom_bar(data = down,aes(x = Protocol,y = Time1,fill = as.integer(Phase)),stat = "identity") + 
    scale_y_continuous(labels = commapos) +
    coord_flip()

The commapos formatter I actually just grabbed from my own existing code from when I've done similar things. You might not want that exact formatting, but the abs(x) is the key part.

Also, note that your Phase variable was a character/factor, and so to get the color bar from your original I had to coerce back to integer.

And, as I mentioned ggplot will complain about stacking not being well defined when using values less than zero. If you try this without separating the data frame into positive/negative values you'll see why.

这篇关于使用ggplot创建一个以零为中心的堆叠条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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