prise6
prise6

Reputation: 146

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?

Upvotes: 10

Views: 4878

Answers (3)

pari
pari

Reputation: 808

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))

`

Upvotes: 2

benformatics
benformatics

Reputation: 21

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)

Upvotes: 2

MLavoie
MLavoie

Reputation: 9836

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)

Upvotes: 9

Related Questions