How to change the colour of the legend by using condition



Hi All,

I have one column named as operators and I am using that operator column to fill (fill=“Operator”). Now I want something like this.

The operator name starts with SEO: Colour should be Red, otherwise colour should be green.

Kindly resolve by showing an example.(By using R ggplot)


Hi @Surya1987,
If I’ve interpreted the problem correctly, the following code could help you.
Assuming you have no problem converting this character variable into a categorical variable for the different SEO type you have.


ggplot(mtcars, aes(x = disp, y = mpg, color = factor(gear))) + geom_point() +
labs(color = “Number of gears”)

You can also change the legend labels from within the factor call

ggplot(mtcars, aes(x = disp, y = mpg, color = factor(gear, labels = c(“Three”,
“Four”, “Five”)))) + geom_point() + labs(color = “Number of gear”)

Hope it helps :slight_smile:



Thanks for quick reply. However your approach will not work here as I want to display all the categories which are present and number of categories might change in future. I just want to change the color of the category bases on the first three letters of the operator name.

I hope you understood my requirement.


So, here’s what i understood. Your data column is susceptible to new factor levels which is based on the first 3 alphabets of the value in that column.

According to this scenario, I suggest you could make another variable which essentially extracts the first three alphabets. And make this variable a category to pass as the color argument inside aesthetic in ggplot.

Don’t hesitate to like if it helped :+1:


Yes I already approached in that way. However It will display only two categories in the legend. I need all the categories to be part of the legend. Only colours needs to be changed.


If you could provide the code snippet in consideration and plots or errors
(if any) that you are getting, I feel it will be helpful to understand the
problem better.


In the attached picture you can see that the regions which started with SEO is shown with red colour otherwise it is green. I want the output in that way.

You can see that all the category of the regions are present. Only colours are different which depends on the first three letter of the region name. Hope it clarifies now.