0

I have a problem with visualizing a ggplot graph. I would love to have different intervals in different colors.

Here is my code:

 ggplot(totalarum,aes(y=Pris,x=Boyta)+
 geom_point() + 
  xlim(100, 200) +
  ylim(1, 10000000) 

so what im after is a solution on how to get, for an example x<=100 to get the color red and 100<x<=200 to be the color blue.

Thanks on advance!

1 Answers1

2

If you have two intervals or only one condition you could map that condition on the color aesthetic and set your desired colors via scale_color_manual:

totalarum <- data.frame(
  Boyta = seq(0, 200, length.out = 20),
  Pris = seq(0, 10000000, length.out = 20)
)

library(ggplot2)

ggplot(totalarum, aes(y = Pris, x = Boyta, color = Boyta <= 100)) +
  geom_point() +
  scale_color_manual(values = c("TRUE" = "red", "FALSE" = "blue"))

EDIT In the more general case where you have multiple intervals I would suggest to add a new column to your dataset using e.g. cut which could then be mapped on the color aes:

library(ggplot2)

totalarum <- data.frame(
  Boyta = seq(0, 500, length.out = 20),
  Pris = seq(0, 10000000, length.out = 20)
)
totalarum$Boyta_cut <- cut(totalarum$Boyta, breaks = seq(0, 500, 100), include.lowest = TRUE, right = TRUE)

colors <- c("red", "blue", "green", "purple", "steelblue")

ggplot(totalarum, aes(y = Pris, x = Boyta, color = factor(Boyta_cut))) +
  geom_point() +
  scale_color_manual(values = colors)

stefan
  • 90,330
  • 6
  • 25
  • 51