如何进行R图分组条形图(带数据标签)?

如何进行R图分组条形图(带数据标签)?,r,plotly,R,Plotly,我正在尝试使用R中的plotly创建分组条形图。我可以使用ggplot创建所需内容,但无法使用ggplotly,因为它无法正确显示负数()。我有两个问题希望你能帮我: 如何使同一组中的酒吧并排?例如,在下面的图中,年龄栏(年轻、中年和老年)不接触,即使这些栏都是年龄组的一部分 另外,如何使每个注释水平居中于与其关联的条上?例如,年龄标签当前在x轴标签年龄上居中,而不是在其各自的条上。如果这是不可能的,那么以某种方式将注释放在x轴下面也会起作用 以下是我目前的代码: # Create exampl

我正在尝试使用R中的plotly创建分组条形图。我可以使用ggplot创建所需内容,但无法使用ggplotly,因为它无法正确显示负数()。我有两个问题希望你能帮我:

  • 如何使同一组中的酒吧并排?例如,在下面的图中,年龄栏(年轻、中年和老年)不接触,即使这些栏都是年龄组的一部分
  • 另外,如何使每个注释水平居中于与其关联的条上?例如,年龄标签当前在x轴标签年龄上居中,而不是在其各自的条上。如果这是不可能的,那么以某种方式将注释放在x轴下面也会起作用
  • 以下是我目前的代码:

    # 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
    
    #创建示例数据
    
    示例_data如果仍然感兴趣,我发现这样的参数:xanchor='right',xshift=-10(向左移动,-10与10个像素相关)对于move label right->xanchor='left',xshift=10也是一样的

    但是注释需要分开: 添加注释(text=Male,xshift=-10…)。。。。
    添加注释(text=Female,xshift=10…

    为什么要
    plot\u ly()
    为什么不
    geom\u bar()
    ?我需要使用plotly,因为绘图是闪亮仪表板的一部分。需要plotly,以便用户可以使用plotly功能,如下载绘图的png、缩放和选择/取消选择组。关于
    gvis
    ?考虑
    添加跟踪
    我可以通过
    添加跟踪
    使条形图按照您的需要排列>但是无法正确获取文本。p.s.使用
    melt
    dcast
    来透视数据。frame.@JustinMeyer您能找到解决方案吗?