Home > other >  R - ggplot lines and columns
R - ggplot lines and columns

Time:10-12

I'm trying to plot a chart that one series is a column and the other is a line with points. When I plot the data using the code below, it plots the way I want. However, there is no legend in the chart. Is there a way to force the legend to appear?

Adding the show.legend = T and the group = xxx makes no difference.

data <- data.frame(
  A = c(1, 2, 3),
  B = c(1, 2, 3),
  C = c(2, 3, 4)
)

ggplot(data, aes(x = A))  
  geom_line(aes(y = C))  
  geom_point(aes(y = C))  
  geom_col(aes(y = B))

enter image description here

CodePudding user response:

I was able to find a solution that is not very elegant, but works for my case.

data.2 <- data.frame(
  A = c(1, 2, 3, 1, 2, 3),
  D = c('B', 'B', 'B', 'C', 'C', 'C'),
  B = c(1, 2, 3, NA, NA, NA),
  C = c(NA, NA, NA, 2, 3, 4)
)

data.2 %>% 
  ggplot(aes(x = A, y = C, col = D, fill = D))  
  geom_line()  
  geom_point()  
  geom_col(aes(y = B))  
  scale_color_manual(values = c('black', 'red'), breaks = c('B', 'C'))  
  scale_fill_manual(values = c('grey', 'transparent'), breaks = c('B', 'C'))

enter image description here

CodePudding user response:

You can keep the same data structure, but it is still awkward, since ggplot doesn't really "want" you to do this (map aesthetics to things that aren't really "real" aesthetics);

ggplot(data = data,aes(x = A))   
  geom_line(aes(y = C,color = "C"))   
  geom_col(aes(y = B,color = "B",fill = "B"),fill = "blue")   
  scale_color_manual(values = c("C" = "red","B" = "blue"))  
  scale_fill_manual(values = c("C" = "red","B" = "blue"))  
  guides(color = guide_legend(override.aes = list(fill = "white")))

What you're trying to accomplish here falls more closely under what ggplot would consider "annotation", i.e. you have two very disparate elements (a line and some bars) and I would typically add annotations in the graph labelling them.

  • Related