Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

How do I set the color bar that does not include values for a given range? Let's say, for instance, I am having the following code:

library(ggplot2)

p2 <- ggplot(mtcars, aes(x=mpg, y=disp, color=hp)) +

  geom_point() +

  scale_color_gradientn(colours = rainbow(4),

  limits=c(50, 100)) +

  scale_x_continuous(limits=c(10,20),

                     breaks =seq(from=10,to=20,by=2))+

  scale_y_continuous(limits=c(70,300),

                     breaks = seq(from = 70, to = 300, by = 20))

p2

With the above code, I receive 7 points which all fall outside the range of color scale (50-100). From that how can I eliminate the points that fall outside the values for color scale? In this example, I should be getting no points in my final plot.

1 Answer

0 votes
by (107k points)

This can be accomplished through the na.value argument in scale_color_gradientn.

library(ggplot2)

p2 <- ggplot(mtcars, aes(x=mpg, y=disp, color=hp)) +

  geom_point() +

  scale_color_gradientn(colours = rainbow(4),

                        limits=c(50, 100), na.value = "transparent") +

  scale_x_continuous(limits=c(10,20),

                     breaks =seq(from=10,to=20,by=2))+

  scale_y_continuous(limits=c(70,300),

                     breaks = seq(from = 70, to = 300, by = 20))

p2

#> Warning: Removed 25 rows containing missing values (geom_point).

If you are a beginner and want to know more about R then do check out the following R programming tutorial.  

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...