将文字阴影/轮廓添加到R中的文字标签中

时间:2020-02-11 21:55:23

标签: r plotly

我想看看是否可以在plotly的{​​{1}}图表的白色文本上添加黑色轮廓。

我找到了以下链接,描述了如何在R中完成该操作,但不确定目前是否可以在plotly.js中完成。 https://github.com/plotly/plotly.js/issues/1597

这是示例图表。

R

Sample Plot

1 个答案:

答案 0 :(得分:1)

据我所知,没有直接方法可以在每个字母上都包含大纲。但是我能够一起破解一些可能使您感兴趣的东西。以下代码段使用两个注释层,其中底层使用深色和粗体字体,而上层通过在要显示的文本中插入空白来略微倾斜。这样产生的效果看起来很像阴影。

情节:

enter image description here

代码

library(plotly)
library(dplyr)

p <- plot_ly(x = c('Product A', 'Product B', 'Product C'), 
        y = c(20, 14, 23), 
        type = 'bar', 
        marker = list(color = 'rgb(158,202,225)',
                           line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  add_annotations(text = c('<b>20</b>', '<b>14</b>', '<b>23</b>'),
                  x = c('Product A', 'Product B', 'Product C'),
                  y = c(20, 14, 23)/2,
                  xref = "x",
                  yref = "y",
                  align='left',
                  font = list(family = 'Times New Roman',
                              size = 24,
                              color = 'black'),

                  showarrow = FALSE) %>%

  add_annotations(text = c('20 ', '14 ', '23 '),
                  x = c('Product A', 'Product B', 'Product C'),
                  y = c(20, 14, 23)/2,
                  xref = "x",
                  yref = "y",
                  #align="right",
                  font = list(family = 'Times New Roman',
                              size = 24,
                              color = 'white'),
                  #bgcolor="black",
                  showarrow = FALSE)


p

如您所见,这些调整大部分是硬编码的,如果可以使用的话,可以使其更加灵活。也许您会发现粗体/非粗体与实际上看起来不错的字体类型的组合?

第二好的方法(或什至是最好的方法)可能只是在bgcolor="black"中加入add_annotations()来得到:

情节:

enter image description here

代码:

library(plotly)
library(dplyr)

p <- plot_ly(x = c('Product A', 'Product B', 'Product C'), 
        y = c(20, 14, 23), 
        type = 'bar', 
        marker = list(color = 'rgb(158,202,225)',
                           line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  add_annotations(text = c(20, 14, 23),
                  x = c('Product A', 'Product B', 'Product C'),
                  y = c(20, 14, 23)/2,
                  xref = "x",
                  yref = "y",
                  font = list(family = 'Arial',
                              size = 14,
                              color = 'rgb(245, 246, 249)'),
                  bgcolor="black",
                  showarrow = FALSE)


p