Home > OS >  Choosing the color of only one of the plotted elements
Choosing the color of only one of the plotted elements

Time:04-09

I'm using ggplot to plot a set of values in R and want to colour them according to their sensor name. However, I'd like to change the colour of one of the sensors (not all of them as they are many). Do you have any suggestions?

I'm going to use the following command:

 ggplot(molted1, aes( Duration,value,group=test )) 
 geom_point(aes(color=sensor))  
 facet_grid(~test,scales = "free")   
 theme_bw()  
 scale_x_continuous(breaks=pretty_breaks(n=3)) 
 theme(legend.position = "none",axis.title=element_text(size=11)) labs(x="",y="Temperature \n(°C)")

CodePudding user response:

One method is to make use of the scale_color_manual()

library(ggplot2)
library(ggthemes)    

   ggplot(molted1, aes(Duration, value, group = test))  
  geom_point(aes(color = sensor), size = 10)   
  facet_grid( ~ test, scales = "free")  
  #theme_bw()  
  #scale_x_continuous(breaks=pretty_breaks(n=3)) 
  scale_color_manual(values = c("AA" = "black", "BB" = "red", "CC"="black"))  
  #theme(legend.position = "none", axis.title = element_text(size =  11))   
  labs(x = "", y = "Temperature \n(°C)")  
  theme_par()  
  theme(
    axis.text.x = element_text(
      hjust = 1,
      face = "bold",
      size = 12,
      color = "black"
    ),
    axis.title.x = element_text(face = "bold", size = 16, color = "black"),
    axis.text.y = element_text(face = "bold", size = 12, color = "black"),
    axis.title.y = element_text(face = "bold", size = 16, color = "black"),
    legend.title = element_blank(),
    legend.text = element_text(
      family = "Times",
      color = "black",
      size = 16,
      face = "bold"
    )
  )

Plot:

enter image description here

Sample data:

 Duration = c(10,2,0,30,40,50)
    value=c(100, 90,34,56,12,1)
    test=c(1,3,1,2,2,3)
    sensor=c("AA","AA","AA","BB", "BB", "CC")
    
    molted1=cbind(Duration, value, test, sensor)
    
    molted1<-data.frame(molted1)
    

CodePudding user response:

One option is to map the color to the logical test of sensor == selected and then supply the background and highlight colors to scale_color_manual().

If you want to more than one sensor to get highlighted and show different colors for just those ones, you may want to take a look at the {gghighlight} package which does this nicely.

library(tidyverse)

mtcars %>% 
  ggplot(aes(disp, mpg))  
  geom_point(aes(color = carb == 4), size = 4)  
  scale_color_manual(values = c("grey50", "red"))  
  facet_grid(~gear)

Created on 2022-04-08 by the reprex package (v2.0.1)

  • Related