plot_ly刻面/网格面板标签和固定高度 [英] plot_ly faceting/trellis panel label and fixed height

查看:220
本文介绍了plot_ly刻面/网格面板标签和固定高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个可爱的ggplot

Suppose I have this lovely ggplot

library(plotly)
library(tidyverse)

mpg2=mpg%>%
  filter(manufacturer%>%as.factor%>%as.numeric<6)%>%
  group_by(manufacturer,model)%>%
  summarize(hwy=mean(hwy))%>%
  mutate(model=reorder(model,hwy))

myggplot=mpg2%>%
  ggplot(aes(x=model,y=hwy))+
  geom_col()+
  coord_flip()+
  facet_grid(manufacturer~.,scales="free",space="free")+
  theme(legend.position="none",
        axis.text.y=element_text(),
        axis.title.y=element_blank(),
        axis.text.x=element_text(size=12),
        strip.text.y = element_text(angle = 0))

myggplot

看起来不错,然后我尝试将其绘图,

looks good, then I try to plotlify it,

ggplotly(myggplot)

三个问题.

  1. 带有1条的小平面上只有一个数字yaxis标签.
  2. 条形图在各个构面上的宽度不同(我的空间="free"参数丢失了).
  3. 标签(y轴标签和构面标签都不在屏幕上.)

那么,我该如何解决?

我也尝试在本地执行此操作,这是我到目前为止所达到的,

I also tried doing it natively, and this is what I have reached so far,

myplotly=mpg2%>%
  nest(-manufacturer)%>%
  mutate(plty=map(data,function(d){
    plot_ly(d,x=~hwy,y=~model,type="bar")   %>%
      layout(showlegend = FALSE)
  }))%>%
  select(plty)%>%
  subplot(nrows=5,shareX=T,heights = table(mpg2$manufacturer)%>%prop.table%>%unname())

myplotly

一个人会如何完成它?

推荐答案

我尝试对ggplotly输出进行一些手动更正:

I tried some manual corrections to the ggplotly output:

library(plotly)
library(tidyverse)

mpg2 <- mpg %>%
  filter(manufacturer %>% as.factor %>% as.numeric<6) %>%
  group_by(manufacturer,model) %>% summarize(hwy=mean(hwy)) %>%
  mutate(model=reorder(model,hwy))

myggplot <- mpg2 %>%  
  ggplot(aes(x=model,y=hwy)) + geom_col() +
  coord_flip() + facet_grid(manufacturer~.,scales="free",space="free") +
  theme(legend.position="none", axis.text.y=element_text(),
        axis.title.y=element_blank(), axis.text.x=element_text(size=12),
        strip.text.y = element_text(angle = 0))

# Set dimensions and margins 
g <- ggplotly(myggplot, height=800, width=1200) %>% 
 layout(autosize=F, margin=list(l=170,r=70,b=50,t=50,pad=10))

# Modify tick labels of Honda bar
g$x$layout$yaxis5$tickvals <- 1:2
g$x$layout$yaxis5$ticktext <- c("civic","")

# Modify widths of Honda and Audi bars
g$x$data[[5]]$width <- g$x$data[[5]]$width/4
g$x$data[[1]]$width <- 3*g$x$data[[1]]$width/4

# Modify positions of facet labels
for (k in seq(2,10,2)) {
  g$x$layout$shapes[[k]]$x1 <- 1.15
}
for (k in 1:6) {
  g$x$layout$annotations[[k]]$xanchor <- "center"
  g$x$layout$annotations[[k]]$x <- 1.0375
}

print(g)

结果比以前更好,但并不完美.
希望它能对您有所帮助.

The result is better than before, but not perfect.
Hope it can help you.

这篇关于plot_ly刻面/网格面板标签和固定高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆