Reorder strings in ggplot

Suppose I have this plot:

library(ggplot2)
pl_data <- data.frame(x = rep(c(1, 2), times = 3), y = c(0, 1, 1, 0, .7, .7), col = rep(c("r", "b", "g"), each = 2))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
  geom_line(size = 3)

Output image

How to change the construction order so that the red line is displayed above the other two?

So the background is that I have stories with very similar lines and want to see certain lines in the foreground.

I assume something according to this answer, the order of stacked bars in ggplot will work. This makes the color column a factor and changes their order, but I would prefer to change it right in the ggplot call bar.

I also tried changing the order of the legends using scale_color_discrete(breaks=c("r", "g", "b"))), but this does not affect the order of construction.

+4
source share
2 answers

, col . , ( ):

pl_data$col <- factor(pl_data$col, c("r", "g", "b"))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
    geom_line(size = 3) + 
    scale_color_manual(values = c(r = "blue", g = "green", b = "red"))

## with standard colors of ggplot2, function taken from:
## http://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette

ggplotColours <- function(n = 6, h = c(0, 360) + 15) {
  if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
  hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
}
pal <- setNames(ggplotColours(3), c("b", "g", "r"))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
    geom_line(size = 3) + 
    scale_color_manual(values = pal, breaks = c("b", "g", "r"))

enter image description here

+5
library(ggplot2)
df <- data.frame(
  x = rep(c(1, 2), times = 3), 
  y = c(0, 1, 1, 0, .7, .7), 
  col = rep(c("r", "b", "g"), each = 2))

ggplot() + 
  geom_line(data = df[3:4,], aes(x = x, y = y), color = 'blue', size = 3) +
  geom_line(data = df[5:6,], aes(x = x, y = y), color = 'green', size = 3) +
  geom_line(data = df[1:2,], aes(x = x, y = y), color = 'red', size = 3)
+1

Source: https://habr.com/ru/post/1676372/


All Articles