2021/04/19

ggplot2 boxplot to ggplotly

   Package "plotly" provide powerful web interactive tools in chart. ggplot2 is very intuitively for creating charts. Use ggplotly to transform ggplot2 object into plotly object is very convenient. But sometimes it's will make you surprised

For example

```{r}
library(ggplot2)
library(plotly)

df <- diamonds
p <- ggplot(df, aes_string(x = 'carat', y = 'cut')) +
  geom_boxplot()
print(p)

```




But the chart will not as you desire if you use ggplotly

 
```{r}
library(ggplot2)
library(plotly)
df <- diamonds
p <- ggplot(df, aes_string(x = 'carat', y = 'cut')) +
  geom_boxplot()
print(ggplotly(p))
```

 


plotly default set boxplot as verticle, so we use coord_flip to plot horizontal boxplot

```{r}
p <- ggplot(df, aes_string(y = 'carat', x = 'cut')) +
  geom_boxplot()+
  coord_flip()
print(ggplotly(p))

```

for grouped boxplot

```{r}
p <- ggplot(df, aes_string(y = 'carat', x = 'cut', color = 'clarity')) +
  geom_boxplot() +
  coord_flip()
print(p)
```


 

use ggplotly get stacked boxplot

```{r}
p <- ggplot(df, aes_string(y = 'carat', x = 'cut', color = 'clarity')) +
  geom_boxplot() +
  coord_flip()
print(ggplotly(p))
```

fine tune ploty layout:

```{r}
p <- ggplot(df, aes_string(y = 'carat', x = 'cut', color = 'clarity')) +
  geom_boxplot() +
  coord_flip()
print(ggplotly(p) %>% layout(boxmode='group'))
```




 

CC Copyright

創用 CC 授權條款
本著作由Chunhung Chou製作,以創用CC 姓名標示-相同方式分享 3.0 Unported 授權條款釋出。