繁体   English   中英

如何制作R绘图分组条形图(带有数据标签)?

[英]How to Make R Plotly Grouped Bar Plot (with Data Labels)?

我正在尝试使用R中的plotly创建一个分组的条形图。我可以用ggplot创建我想要的东西,但由于它无法正确显示负数的问题而无法使用ggplotly( https://github.com / ropensci / plotly / issues / 560 )。 我有两个问题希望您能提供帮助:

  1. 如何使同一组中的条并排放置? 例如,在下面的图中,年龄条(Young,Middle和Old)没有接触,即使这些条都属于Age组。
  2. 另外,如何使每个注释在与之关联的条上水平居中? 例如,年龄标签当前位于x轴标签Age上方,而不是其各自的条形上方。 如果这不可能,则以某种方式在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

绘图分组条形图示例

如果仍然感兴趣,我会找到这样的参数: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 ....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM