简体   繁体   中英

Make a line separated by group in bar chart in GGplot

I am trying to overlay two sets of data that with be used in bar charts. The first is the main set of data and I want that to be the main focus. For the second dataset I want just a line marking where on the chart it would be. I can get close to what I want by doing this:

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

I believe I can accomplish what I want by using geom_vline if there is a way to separate it by groups. Another option I came up with is if it is possible to change the colors of the "sides" of the bars in the overlay to white while keeping the "top" of each bar chart as black.

An idea of what I want (Edited in paint)

You could use geom_errorbar where the ymin and ymax are the same values like this:

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()

Created on 2022-12-28 with reprex v2.0.2

Another option is geom_point with shape = 95 (line) and the size adjusted to suit:

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()

Created on 2022-12-28 with reprex v2.0.2

Here is one more using geom_segment() . Some would say to fancy, but anyway: For this we have to extend 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()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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