Ggplotly displays negative bars in a positive direction

I use the geom_bar chart in ggplotly and it makes negative positive bars. Any ideas why this might be the case, and in particular how to solve it?

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)

Why will the first bar be in a positive direction with a negative value?

The versions I use are the latest:

plotly_3.4.13

ggplot2_2.1.0

+4
source share
2 answers

If you write the plotly object to another variable, you can change the plot properties, including the "data" that it uses to render the graph.

In your specific example, add this to your code:

#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

+3
source

, , . :

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

- ... .

0

All Articles