2016-05-17 33 views
4

我在ggplotly中使用了一个geom_bar绘图图形,并将负向条形图呈现为正数。任何想法为什么这可能是这种情况,特别是如何解决这个问题?ggplotly在正方向上绘制负向条形图

library(ggplot2) 
library(plotly) 
dat1 <- data.frame(
    sex = factor(c("Female","Female","Male","Male")), 
    time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")), 
    total_bill = c(-13.53, 16.81, 16.24, 17.42) 
) 

# Bar graph, time on x-axis, color fill grouped by sex -- use position_dodge() 
g <- ggplot(data=dat1, aes(x=time, y=total_bill, fill=sex)) + 
    geom_bar(stat="identity", position=position_dodge()) 
ggplotly(g) 

为什么第一个柱子会处于正向,负值?

,我使用的版本是最新的:

plotly_3.4.13

ggplot2_2.1.0

+4

看起来像这是一个'ggplotly'的已知问题(https://github.com/ropensci/plotly/issues/560) – joemienko

+0

啊我看到了...那是不幸的。有关避免这个问题的任何建议,而不是打开阴谋(例如通过更改某些规范)?或者最好等待修复? – Nick

+0

我认为这取决于您的具体使用情况 - 您确定需要积极使用吗? – joemienko

回答

3

如果你写你的plotly对象另一个变量可以修改plotly属性,包括'数据“来渲染剧情。

为了您的具体的例子把这段代码:

#create plotly object to manipulate 
gly<-ggplotly(g) 

#confirm existing data structure/values 
gly$x$data[[1]] 
# see $y has values of 13.53, 16.81 which corresponds to first groups absolute values 

#assign to original data 
gly$x$data[[1]]$y <- dat1$total_bill[grep("Female",dat1$sex)] 

#could do for second group too if needed 
gly$x$data[[2]]$y <- dat1$total_bill[grep("Male",dat1$sex)] 

#to see ggplotly object with changes 
gly 

enter image description here

0

我想出了其中使用小包装在案件工作有一个大致的解决方案。这是问题的玩具数据为例:

set.seed(45) 

df <- data.frame(group=rep(1:4,5), TitleX=rep(1:5,4), TitleY=sample(-5:5,20, replace = TRUE)) 

h <- ggplot(df) + geom_bar(aes(TitleX,TitleY),stat = 'identity') + facet_wrap(~group) 

h 

Fake Data with Negatives

当我们使用ggplotly我们看到的OP锯,这是底片已经消失:

gly <- ggplotly(h) 
gly 

Where did the negatives go?

我写了一个函数,它将检查每个方面列表中的实例,其中文本中的y值被赋值为0,这似乎是

fix_bar_ly <- function(element,yname){ 
    tmp <- as.data.frame(element[c("y","text")]) 
    tmp <- tmp %>% mutate(
    y=ifelse(grepl(paste0(yname,": 0$"),text), 
      ifelse(y!=0,-y,y), 
      y) 
) 
    element$y <- tmp$y 
    element 
} 

现在我把这个函数的数据每个面:有一个我目前正在处理共病问题

data.list <- gly$x$data 
m <- lapply(data.list,function(x){fix_bar_ly(x,"TitleY")}) 
gly$x$data <- m 
gly 

enter image description here

出于某种原因,条之间的空间已经消失......但是在适当的地方至少这些价值观是消极的。

相关问题