绘图层控制:如何在形状前面添加文本

时间:2019-05-09 20:03:11

标签: r plotly

我正在使用plotly显示一些形状并在其上添加一些注释(文本)。但是,我不知道如何控制图层排序以按图方式绘制对象,并且文本始终位于形状后面(我在图式R API文档中没有找到任何示例)。

以下是一个可重复的示例:

library("plotly")

shapes <- list(
  list(type = "rect",
       fillcolor = "red", line = list(color = "white"),
       x0 = 0.0, x1 = 0.5, xref = "x",
       y0 = 0.0, y1 = 1.0, yref = "y",
       opacity = 0.3),
  list(type = "rect",
       fillcolor = "grey", line = list(color = "white"),
       x0 = 0.5, x1 = 1.0, xref = "x",
       y0 = 0.0, y1 = 1.0, yref = "y",
       opacity = 0.98)
)

plot_ly() %>%
  layout(shapes = shapes) %>%
  add_text(x = c(0.25, 0.75), y = 0.5, text = c("Easy Visible", "Barely visible"), textfont = list(color = '#000000'))

这将产生以下输出(使用不透明度参数,我们可以看到文本位于形状的后面):

enter image description here

关于如何在不透明形状前面添加文本的任何想法?

2 个答案:

答案 0 :(得分:2)

layer="below"添加shapes选项。它指定是在轨迹的下方还是上方绘制形状。

shapes <- list(
  list(type = "rect",
       fillcolor = "red", line = list(color = "white"),
       x0 = 0.0, x1 = 0.5, xref = "x",
       y0 = 0.0, y1 = 1.0, yref = "y",
       opacity = 0.3, layer="below"),
  list(type = "rect",
       fillcolor = "grey", line = list(color = "white"),
       x0 = 0.5, x1 = 1.0, xref = "x",
       y0 = 0.0, y1 = 1.0, yref = "y",
       opacity = 0.98, layer="below")
)

plot_ly() %>%
  layout(shapes = shapes) %>%
  add_text(x = c(0.25, 0.75), y = 0.5, 
           text = c("Easy Visible", "Barely visible"), 
           textfont = list(color = '#000000'))

enter image description here

答案 1 :(得分:2)

一种选择是使用注释而不是文本:

plot_ly() %>%
  layout(shapes = shapes) %>% 
  add_annotations( x = c(0.25, 0.75), 
                   y = c(0.5, .5),
                   xref = "x",
                   yref = "y",
                   text = c('Easy Visible', 'Also Easy Now'),
                   font = list(color = '#000000'), showarrow = F)

enter image description here