Make Grouped Bar Plot? With Data Labels?


I’m trying to create a grouped bar plot with plotly in R. I can create what I want with ggplot but I can’t use ggplotly because of the issue where it does not display negative numbers correctly ( I have two questions that I am hoping you can help with:

  1. Can you explain how to make it so that the bars that are in the same group are side by side? For example, in the plot below the Age bars (Young, Middle, and Old) are not touching even though those bars are all part of the Age group.

  2. Also, how can I have each annotation horizontally centered over the bar it is associated with? For example, the age labels are currently centered over the x axis label Age rather than over their respective bars. If this is not possible having the annotation underneath the x axis in some way would also work.

Here’s my code so far:
# Create example data
example_data <-, 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"
) %>%
    # 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)