1

Let's say I'm creating the grouped barplot by something like this:

data <- data.frame(time = factor(1:3), type = LETTERS[1:4], values = runif(24)*10)
ggplot(data, aes(x = type, y = values, fill = time)) +
  stat_summary(fun=mean, geom='bar', width=0.55, size = 1, position=position_dodge(0.75))

Inside each type I want to connect all bar tops (meaning to connect 3 bars for A, 3 bars for B, and so on) with the line. I'd like to get something like that as a result: enter image description here

Is there a way to do that ? Thank you!

1 Answer 1

1

I changed the code to another logic that I prefer, that is to prepare the data before using ggplot().

Code

library(dplyr)
library(ggplot2)

data <- data.frame(time = factor(1:3), type = LETTERS[1:4], values = runif(24)*10)

pdata <- data %>% group_by(type,time) %>% summarise(values = mean(values,na.rm = TRUE)) %>% ungroup()

pdata %>% 
  ggplot(aes(x = type, y = values)) +
  geom_col(
    mapping = aes(fill = time, group = time),
    width = 0.55,
    size = 1,
    position = position_dodge(0.75)
  )+
  geom_line(
    mapping = aes(group = type),
    size = 1,
    position = position_dodge2(.75)
  )

Output

enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much, Vinicius! I actually meant to connect 3 bars inside one type. Meaning, mean values for red, green and blue bars with one line in A, another similar line for B, then one for C and one for D. Is it possible ? Thank you!
I guess the difficulty here is that x parameter is needed to create line across x coordinates. And here it's required to create the line "inside" one coordinate (like for all bars inside A coordinate)
Sorry I did not understand how is your desired output? Can you maybe draw something?
Thank you, Vinicius! Yep, please, see the example picture in the question. Thanks a lot !
Now I got it, I updated my code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.