【问题标题】:Nested ggplot histograms instead of cumulative嵌套的ggplot直方图而不是累积的
【发布时间】:2021-10-08 09:00:48
【问题描述】:

使用这张表:

  Groups variable value
1     G1     VAR1  75.0
2     G1     VAR2  37.5
3     G2     VAR1  50.0
4     G2     VAR2  12.5

还有这段代码:

color_list <- c("VAR1"="blue","VAR2"="red")

tab %>%
  mutate(Groups = fct_reorder(Groups, value)) %>%
  ggplot( aes(x=value, y=Groups,fill=factor(variable, levels = c("VAR1","VAR2")),label=Groups))  +
  scale_fill_manual(values = color_list[unique(tab$variable)], guide = guide_legend(order = 1)) +  theme_minimal()

我设法得到下图:

但这是我所期望的:

如您所见,它是我需要的嵌套直方图,而不是累积直方图表示。

有人知道如何使用 ggplot2 来实现吗?

如果有帮助,这里是 dput 格式的表格数据:

structure(list(Groups = c("G1", "G1", "G2", "G2"), variable = c("VAR1", 
"VAR2", "VAR1", "VAR2"), value = c(75, 37.5, 50, 12.5)), class = "data.frame", row.names = c(NA, 
-4L))

【问题讨论】:

  • 不知何故,我希望直方图可以绘制计数,但不确定 37.5 的值在这种情况下可能意味着什么。您能否确认它是否真的是您想要的直方图?
  • 当然,我编辑了代码。事实上,我只想绘制每个变量类别的计数,其中 VAR1(蓝色)应该在后台,VAR2(红色)应该在前台。

标签: r ggplot2


【解决方案1】:

你可以尝试这样的事情,混合你的代码,dario给出的提示和其他东西:

library(ggplot2)
library(dplyr)
library(forcats)

color_list <- c("VAR1"="blue","VAR2"="red")

tab %>%
  mutate(Groups = fct_reorder(Groups, value)) %>%
  ggplot( aes(x = Groups, y = value, 
              fill  = factor(variable, levels = c("VAR1","VAR2")), 
              group = variable, 
              label = value)) +
  # here you overlap your bars
  geom_bar (stat="identity", position = position_dodge(width = 0)) +
  # here custom colors
  scale_fill_manual(values = color_list[unique(tab$variable)], 
                    guide  = guide_legend(order = 1)) +
  # y (x) axis as you've pointed out, values and 30 by 30 labels, you can 
  # customize it of course
  scale_y_continuous("value", labels =c(seq(from = 0, to = 90, by = 30),tab$value), breaks = c(seq(from = 0, to = 90, by = 30),tab$value)) +  
  # some frills
  theme_minimal() +
  coord_flip() +
  labs(fill = "title")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2013-08-23
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多