如何在条形图中使用 add_annotations

How to use add_annotations in a bar chart

我需要帮助在使用 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)')))

我想在图表中的条形末端添加 "s_1" 的值,如下图所示,但对于每个条形。

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

轻轻求代码,我知道应该很简单。

我们可以使用:

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

您可能想尝试不同的属性:

Valid attributes include:

'type', 'visible', 'showlegend', 'legendgroup', 'opacity', 'name', 'uid', 'hoverinfo', 'stream', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'text', 'mode', 'hoveron', 'line', 'connectgaps', 'fill', 'fillcolor', 'marker', 'textposition', 'textfont', 'r', 't', 'error_y', 'error_x', 'xaxis', 'yaxis', 'xsrc', 'ysrc', 'textsrc', 'textpositionsrc', 'rsrc', 'tsrc', 'key'

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

通常注释会在栏的中间,将 xanchor 设置为 left 可以解决这个问题,但是你的负值很难看到。

建议的解决方案:

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

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))