Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 + plotly : Axis title disappear

I've got an issue when using ggplotly() to a ggplot graph: the y axis disappears. Here's a reproducible example using iris dataset (this example is quite dump, but whatever)

data(iris)
g = ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, fill = Species)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  scale_fill_manual(name = "legend", values = c("blue", "red", "green")) +
  ylab("Y title") +
  ylim(c(0,3)) +
  xlab("X title") +
  ggtitle("Main title")
g
ggplotly(g)

As you can see, the Y axis title vanished.

Well, if ylim is deleted it works, but I'd like to specify y limits.

I tried to do the following:

data(iris)
g = ggplot(data = iris, aes(x = Petal.Length, y = Petal.Width, fill = Species)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  scale_fill_manual(name = "legend", values = c("blue", "red", "green")) +
  scale_y_continuous(name = "Y title", limits = c(0, 3)) +
  xlab("X title") +
  ggtitle("Main title")
g
ggplotly(g)

But now it's the legend title that doesn't fit.

My config : R 3.2.0, plotly 2.0.16, ggplot2 2.0.0

In both examples the graph given by ggplot is what I want, but ggplotly gives something else. Is it an issue, is there a workaround?

like image 884
prise6 Avatar asked Feb 02 '16 14:02

prise6


3 Answers

I am not sure why it's happening but here is a work around. It will give you what you want.

p <- ggplotly(g)
x <- list(
    title = "X Title"
)
y <- list(
    title = "Y Title"
)
p %>% layout(xaxis = x, yaxis = y)
like image 196
MLavoie Avatar answered Oct 19 '22 18:10

MLavoie


I was having a similar problem. A ggplot object pushed through ggplotly was exhibiting clipping of my y-axis label [in a Shiny app].

To fix it, I did what MLavoie suggested but then it had BOTH my ggplot labels and my ggplotly labels. To fix this I simply set my ggplot labels to spaces and everything worked (if you set them to nothing, the plotly labels will overlap with the axis tick-mark values).

p <- ggplotly(g + ylab(" ") + xlab(" "))
x <- list(
    title = "X Title"
)
y <- list(
    title = "Y Title"
)
p %>% layout(xaxis = x, yaxis = y)
like image 30
benformatics Avatar answered Oct 19 '22 16:10

benformatics


I had the same problem, thanks to your comments, i could resolve it. However I had the issue that labels of axis were attached to the plot. So i resolved it by adding margin.

p <- ggplotly(g + ylab(" ") + xlab(" "))
x <- list(
title = "X Title")
y <- list(
title = "Y Title")
p %>% layout(xaxis = x, yaxis = y, margin = list(l = 75, b =50))

`

like image 30
pari Avatar answered Oct 19 '22 17:10

pari