2017-02-13 18 views
0

我需要帮助,在图表栏上添加一些注释,使用plotly构建。如何在条形图中使用add_annotations

我有以下的数据帧 “小号”:

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

我要添加的图表中的“s_1”值在条的末尾,如下图所示,但是对于每个条。

enter image description here

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

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

回答

2

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

通常情况下,注释会在栏的中间位置,将xanchor设置为left修复了该问题,但您的负值很难看清。

建议解决方案:

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

我们可以使用:

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

您可能需要具有不同属性的发挥:

有效属性包括:

'型', '看得见', '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”,“台橡”,“关键”

+0

实际添加文本,但它完全错过了正确的位置。你知道如何解决这个问题吗? – smars

相关问题