如何制作R Plotly Grouped Bar Plot(带数据标签)?

时间:2017-06-16 18:38:22

标签: r plotly

我正在尝试用R中的情节创建一个分组条形图。我可以使用ggplot创建我想要的但我不能使用ggplotly因为它没有正确显示负数的问题({{3} })。我有两个问题希望你可以提供帮助:

  1. 如何制作同一组中的条形并排?例如,在下面的图表中,年龄栏(年轻人,中年人和老年人)都没有接触,即使这些酒吧都是年龄组的一部分。
  2. 另外,如何将每个注释水平居中于与其关联的栏上?例如,年龄标签当前以x轴标签Age为中心而不是其各自的条形。如果不可能以某种方式在x轴下面进行注释也可以。
  3. 到目前为止,这是我的代码:

    # Create example data
    example_data <- as.data.frame(matrix(NA, 9, 3))
    names(example_data) <- c("group", "subgroup", "value")
    example_data$group <- c("Gender", "Gender", "Race", "Race", "Race", "Age", "Age", "Age", "Human")
    example_data$subgroup <- c("Female", "Male", "Asian", "Black", "White", "Young", "Middle", "Old", "Yes")
    example_data$value <- c(11, 14, 72, 12, 82, 22, 30, 4, 5)
    
    # Create chart
    p <- plot_ly(
      data = example_data,
      x = ~group,
      y = ~value,
      color = ~subgroup,
      type = "bar"
    ) %>%
      layout(
        # xaxis = list(type="category"), # Doesn't seem to do anything
        # barmode = "group", # Doesn't seem to do anything
        showlegend = FALSE
    ) %>%
    add_annotations(text = ~subgroup,
                    x = ~group,
                    y = ~value / 2, # Center vertically on the bar
                    # xref = "x", # Doesn't seem to do anything
                    # yref = "y", # Doesn't seem to do anything
                    # xanchor = 'center', # Doesn't seem to do anything
                    # yanchor = 'bottom', # Doesn't seem to do anything
                    showarrow = FALSE)
    
    p
    

    https://github.com/ropensci/plotly/issues/560

1 个答案:

答案 0 :(得分:0)

如果仍然感兴趣,我发现了以下参数:xanchor ='right',xshift = -10(向左移动,-10与10像素有关)与向右移动标签相同-> xanchor ='left',xshift = 10

https://github.com/plotly/plotly.js/blob/master/src/components/annotations/attributes.js

但是注释需要分开: add_annotations(text = Male,xshift = -10 .... add_annotations(text = Female,xshift = 10 ....