R语言 在条形图中按组分隔线

prdp8dxp  于 2022-12-30  发布在  其他
关注(0)|答案(3)|浏览(200)

我试图覆盖两组将在条形图中使用的数据。第一组是主数据集,我希望它成为主要焦点。对于第二个数据集,我只希望用一条线标记它在图表中的位置。我可以通过执行以下操作来接近我所需的内容:

Tbl = data.frame(Factor = c("a","b","c","d"),
                 Percent = c(43,77,37,55))

Tbl2 = data.frame(Factor = c("a","b","c","d"),
                  Percent = c(58,68,47,63))

ggplot(aes(x = Factor, y = Percent), data = Tbl) + 
  geom_bar(position = "stack", stat = "identity", fill = "blue") +
  ylim(0,100) +
  geom_bar(aes(x = Factor, y = Percent), data = Tbl2,
           position = "stack", stat = "identity", fill = NA, color = "black") +
  theme_bw()

What I have so far
我相信如果有一种方法可以将其按组分开,我可以通过使用geom_vline来完成我想要的。我想到的另一个选项是,是否可以将覆盖图中条形的“边”的颜色更改为白色,同时将每个条形图的“顶”保持为黑色。
我想要什么的想法(用绘画编辑)

6ovsh4lw

6ovsh4lw1#

您可以使用geom_errorbar,其中ymin和ymax的值相同,如下所示:

library(ggplot2)
ggplot(aes(x = Factor, y = Percent), data = Tbl) + 
  geom_bar(position = "stack", stat = "identity", fill = "blue") +
  ylim(0,100) +
  geom_errorbar(aes(x = Factor, ymin = Percent, ymax = Percent), data = Tbl2,
                stat = "identity", color = "black") +
  theme_bw()

创建于2022年12月28日,使用reprex v2.0.2

wnrlj8wa

wnrlj8wa2#

另一个选项是带有shape = 95(线)的geom_point,并调整大小以适应:

library(tidyverse)

Tbl = data.frame(Factor = c("a","b","c","d"),
                 Percent = c(43,77,37,55))

Tbl2 = data.frame(Factor = c("a","b","c","d"),
                  Percent = c(58,68,47,63))

ggplot(aes(x = Factor, y = Percent), data = Tbl) + 
  geom_bar(position = "stack", stat = "identity", fill = "blue") +
  ylim(0,100) +
  geom_point(aes(x = Factor, y = Percent), data = Tbl2,
           position = "stack", stat = "identity", color = "black", shape = 95, size = 30) +
  theme_bw()

创建于2022年12月28日,使用reprex v2.0.2

new9mtju

new9mtju3#

下面是另一个使用geom_segment()的例子。有些人会说太花哨了,但无论如何:为此,我们必须扩展Tbl2

library(ggplot2)
library(dplyr)

ggplot(aes(x = Factor, y = Percent), data = Tbl) + 
  geom_bar(position = "stack", stat = "identity", fill = "blue") +
  ylim(0,100) +
  geom_segment(data = Tbl2 %>% 
                 mutate(x = c(0.55, 1.55, 2.55, 3.55),
                        xend = x+0.9), aes(x=x,xend=xend, y = Percent, yend=Percent), size=2)+
  theme_bw()

相关问题