情节:如何使用R和Shiny为子图创建单个y轴标签?

时间:2020-07-30 15:44:01

标签: r plotly yaxis

如何添加Y轴标题“数千人”以覆盖整个图形,而不是单个子图行?下图显示了Y轴标题(如果绘图的话)在底部缩小。我想要一个y轴标签,该标签位于整个图表的中间,而不是子图行的中间。奖金:在允许布局的同时保持y轴标题方向(自动调整大小= TRUE)。

library(plotly)
  plotList <- function(nplots) {
   lapply(seq_len(nplots), function(x) {
    plot_ly(economics, x = ~date, y = ~unemploy)%>%
      add_annotations(
        text = ~paste("Plot ",x),
        x = 0.5,
        y = 1.1,
        yref = "paper",
        xref = "paper",
        xanchor = "middle",
        yanchor = "top",
        showarrow = FALSE)
  }
    )
}
s1 <- subplot(plotList(4), nrows = 4, shareX = TRUE, shareY = TRUE, titleY = FALSE, margin = .01)
s2 <- subplot(plotList(2), shareY = TRUE)
fig <- subplot(s1, s2, 
               plot_ly(economics, x = ~date, y = ~unemploy)%>%
                 layout(yaxis = list(title = 'Total Unemployed Persons')), 
                        nrows = 3, 
                        margin = 0.04, heights = c(0.6, 0.3, 0.1),
                        titleY = TRUE)

fig

原始图表: enter image description here

期望图表: enter image description here 这些链接可能会帮助尝试回答以下问题的任何人:r plotly communitypython plotly community

2 个答案:

答案 0 :(得分:0)

有人问过类似的问题并回答了Python。对于R,解决方案相同。只需删除标准轴标签,然后将所需信息显示为注释即可。下图由下面的代码段产生,并在Google.Apis.Docs.v1.Data.Bodyy=0.5

处插入垂直注释

enter image description here

完整代码:

x=-0.2

答案 1 :(得分:0)

我建议使用'xshift'参数保留动态调整大小。否则,保持背地的建议不变,但是在注释中设置“ x = 0”和“ xshift = -50”:

fig1 <- plot_ly(economics, x = ~date, y = ~unemploy)
fig1 <- fig1 %>% add_lines(name = ~"unemploy")
fig2 <- plot_ly(economics, x = ~date, y = ~uempmed)
fig2 <- fig2 %>% add_lines(name = ~"uempmed")
fig <- subplot(nrows=2,fig1, fig2)



# make room for both main title and y-axis titles
m <- list(
  l = 100,
  r = 25,
  b = 25,
  t = 125
  #pad = 4
)
fig <- fig %>% layout(title=list(text='Main figure title', font = list(color = "red",size = 24)),
                      autosize = T,
                      #width = 500, height = 500,
                      margin = m)


# your axis title
fig <- fig %>% layout(annotations = list(
  list(x = 0 , y = 0.5, text = "Thousands of people",
       xshift = -50,
       font = list(color = "blue",size = 18),
       textangle = 270,
       showarrow = F, xref='paper', yref='paper', size=48)
  
))

fig

此处记录了xshift供参考:https://plotly.com/r/reference/layout/annotations/#layout-annotations-items-annotation-xshift