user19402456
user19402456

Reputation: 55

How to apply different colors for point and text but in the same group?

I am trying to draw a plot in which the colors of the points are red, green, blue for 3 groups and colors of the associated labels are darkred, darkgreen, darkblue.

I tried the following code, but the dark colors are not used.

library(ggplot2)
ggplot(data.frame("Year" = 2013:2022, 
                  "Value" = round(rnorm(10), 1), 
                  "Group" = sample(letters[1:3], 10, T)),
       aes(Year, Value)) + 
  geom_point(aes(color = Group)) +
  geom_text(aes(label = Value, color = Group), vjust = -1, show.legend = FALSE) +
  scale_color_manual(values = c("red", "green", "blue", "darkred", "darkgreen", "darkblue"))

Upvotes: 3

Views: 1092

Answers (2)

M--
M--

Reputation: 29238

We can use fill instead of color for points and set the shape to 21. If you don't want the border around the points, add stroke = NA to geom_point.

library(ggplot2)
ggplot(data.frame("Year" = 2013:2022, 
                  "Value" = round(rnorm(10), 1), 
                  "Group" = sample(letters[1:3], 10, T)),
       aes(Year, Value)) + 
  geom_point(aes(fill = Group), pch=21) +
  geom_text(aes(label = Value, color = Group), vjust = -1, 
            show.legend = FALSE) +
  scale_color_manual(values = c("darkred", "darkgreen", "darkblue")) +
  scale_fill_manual(values = c("red", "green", "blue"))

Upvotes: 1

Jeremy Holden
Jeremy Holden

Reputation: 71

I found the ggnewscale package that seems to do what you want. https://ggplot2.tidyverse.org/articles/faq-customising.html#colours

library(ggplot2)
library(ggnewscale)
#> Warning: package 'ggnewscale' was built under R version 4.1.3
ggplot(data.frame("Year" = 2013:2022, 
                  "Value" = round(rnorm(10), 1), 
                  "Group" = sample(letters[1:3], 10, T)),
       aes(Year, Value)) + 
  geom_point(aes(color = Group)) +
  scale_color_manual(values = c("red", "green", "blue")) +
  new_scale_color() + 
  geom_text(aes(label = Value, color = Group), vjust = -1, show.legend = FALSE) +
  scale_color_manual(values = c("darkred", "darkgreen", "darkblue"))

Created on 2022-06-29 by the reprex package (v2.0.1)

Upvotes: 3

Related Questions