首页 > 解决方案 > 如何让 plotly::ggplotly 不将 boxplot x 轴标签转换为数值

问题描述

我想了解如何plotly::ggplotly保留x 轴标签而不将它们转换为数值?data.frame我将 my中用于标签的列转换x-axis为字符,以确保它们不是因素。会发生以下情况:

我想知道如何plotly::ggplotly正确显示 x 轴标签?

我已经对此进行了一些搜索,但没有找到任何东西。

以下是一些关键版本(软件包、操作系统等):

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

正确的 X 轴标签

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

在此处输入图像描述

X 轴标签不正确

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

在此处输入图像描述

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

正确的 X 轴标签

在此处输入图像描述

标签: rggplot2ggplotly

解决方案


问题在于 ; 的版本plotly。从更新plotly_4.9.0plotly_4.9.2.1修复问题。plotlyafter的任何版本都4.9.0可能解决问题,但我没有测试过,我只能确认4.9.2.1为我解决了问题。

固定 X 轴标签图


推荐阅读