Search code examples
rggplot2ggplotly

How to get plotly::ggplotly to not convert boxplot x-axis labels to numeric values


I would like to understand how I can get plotly::ggplotly to keep the x-axis labels and not convert them to numeric values? I converted the column in my data.frame, used for the x-axis labels, to characters to ensure they are not factors. What happens is the following:

  • The first plot below (ggplot) shows the x-axis labels displayed correctly.
  • Using the ggplot object above, plotly::ggplotly is called and the results are that the x-axis labels are displayed incorrectly (as numeric values).
  • The third plot shows the same data plotted using plotly directly (i.e. not using plotly::ggplotly); this displays the correct results.

I would like to know how I can get plotly::ggplotly to display the x-axis labels correctly?

I have done some searching for this but didn't find anything.

Here are some of the key versions (packages, OS, etc.):

R version 3.6.0 (2019-04-26)
Platform: x86_64-pc-linux-gnu (64-bit)

[1] plotly_4.9.0
[1] ggplot2_3.3.0

Correct X-Axis Labels

library(dplyr)
### Convert "Species" column to character (i.e. ensure it is NOT a factor).
iris.v2 <- iris %>% dplyr::mutate(Species = as.character(Species))
str(iris.v2)

### Shows that Species is a "chr" type.
# 'data.frame': 150 obs. of  5 variables:
# $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
# $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
# $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
# $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# $ Species     : chr  "setosa" "setosa" "setosa" "setosa" ...

### Correct x-axis labeling: Plot data using ggplot.
plt.iris <-
  iris.v2 %>%
  ggplot2::ggplot(aes(as.character(Species), Petal.Width)) +
  ggplot2::geom_boxplot()
plt.iris

enter image description here

Incorrect X-Axis Labels

### Incorrect x-axis labeling: plot above plot with ggplotly.
pltly.iris <-
  plotly::ggplotly(plt.iris)
pltly.iris

enter image description here

### Correct x-axis labeling: Plot data using plotly directly.
native.pltly.iris <-
  plotly::plot_ly(iris.v2, x = ~Species, y = ~Petal.Width, type = "box")
native.pltly.iris

Correct X-Axis Labels

enter image description here


Solution

  • The issue is with the version of plotly; updating from plotly_4.9.0 to plotly_4.9.2.1 fixes the issue. It is possible that any version of plotly after 4.9.0 may fix the issue, but I have not tested that, I can only confirm that 4.9.2.1 fixes the issue for me.

    Fixed-X-Axis-Labels-Plot