如何在条形图中使用add_annotations

时间:2017-02-13 15:48:10

标签: r text graph bar-chart plotly

我需要帮助才能在使用plotly构建的图表栏上添加一些注释。

我有以下数据框" s ":

s_0 <- c("NH", "OR", "NE", "PA", "NJ", "MA", "IL", "CA", "WI", "OH", "WV")
s_1 <- c(0.66719, 0.62480, 0.62797, 0.55121, 0.25582, 0.63407, 0.57009, 0.29712, 0.19979, 0.08913, -0.16944)
s <- data.frame(s_0, s_1)

我使用plot_ly()生成以下条形图:

s_plot <- plot_ly(x = ~s_1, y = reorder(s_0, s_1),
type = 'bar',
orientation = 'h',
marker = list(color = 'rgba(50, 50, 100, 1)',
line = list(color = 'rgba(128, 0, 128)')))

bar chart

我想添加&#34; s_1&#34;的值在条形图末尾的图表中,如下图所示,但每个条形图。

enter image description here

我想我必须使用add_annotations(),但我不知道该怎么做。

我轻轻地问代码,我知道它应该很简单。

2 个答案:

答案 0 :(得分:2)

您的代码的修改和Plotly提供的example几乎提供了正确的布局。

通常情况下,注释会在条形图的一半处,将问题设置为xanchorleft,但是很难看出您的负值。

建议的解决方案:

xanchor = ifelse(s_1 > 0, 'left', 'right')

enter image description here

library(plotly)

s_0 <- c("NH", "OR", "NE", "PA", "NJ", "MA", "IL", "CA", "WI", "OH", "WV")
s_1 <- c(0.66719, 0.62480, 0.62797, 0.55121, 0.25582, 0.63407, 0.57009, 0.29712, 0.19979, 0.08913, -0.16944)
s <- data.frame(s_0, s_1)

s_plot <- plot_ly(x = ~s_1, y = reorder(s_0, s_1),
                  type = 'bar',
                  orientation = 'h',
                  marker = list(color = 'rgba(50, 50, 100, 1)',
                                line = list(color = 'rgba(128, 0, 128)')))  %>%
  layout(annotations = list(x = s_1, y = reorder(s_0, s_1), text = s_1, xanchor = ifelse(s_1 > 0, 'left', 'right'),
                             yanchor = 'center',
                            showarrow = FALSE))

答案 1 :(得分:0)

我们可以使用:

add_text(s_plot, text = s_1, marker = NULL, textposition = 'right')

您可能想要使用不同的属性:

  

有效属性包括:

     

&#39;键入&#39;,&#39;可见&#39;,&#39; showlegend&#39;,&#39; legendgroup&#39;,&#39; opacity&#39;,&# 39;名称&#39 ;,   &#39; uid&#39;,&#39; hoverinfo&#39;,&#39; stream&#39;,&#39; x&#39;,&#39; x0&#39;,&#39; dx& #39;,&#39; y&#39;,&#39; y0&#39;,&#39; dy&#39;,   &#39; text&#39;,&#39;模式&#39;,&#39; hoveron&#39;,&#39; line&#39;,&#39; connectgaps&#39;,&#39; fill& #39;,&#39; fillcolor&#39;,   &#39;标记&#39;,&#39; textposition&#39;,&#39; textfont&#39;,&#39; r&#39;,&#39; t&#39;,&#39; error_y& #39;,&#39; error_x&#39;,   &#39; xaxis&#39;,&#39; yaxis&#39;,&#39; xsrc&#39;,&#39; ysrc&#39;,&#39; textsrc&#39;,&#39; textpositionsrc& #39 ;,   &#39; rsrc&#39;,&#39; tsrc&#39;,&#39; key&#39;