Assigning Specific Colors to Specific Values

Hello,

I was wondering what is the best way to assign specific colors to specific values. Thanks for your help!

oyaa <- data.frame(
plate_x = c(-0.205, -0.017, -0.902, 0.229, -0.909, 0.903, 0.119, 0.787,
-0.581, 0.913, 0.902, -0.881, -0.791,
-0.943, -0.192, 0.912, -1.398, 0.383, -0.057,
-0.487),
plate_z = c(2.779, 3.339, 2.606, 1.678, 1.999, 3.689, 1.339, 2.881, 2.891,
3.774, 2.441, 2.491, 2.488, 1.688, 2.388,
3.981, 1.632, 2.879, 2.516, 2.798),
pitch = as.factor(c("fastball", "fastball", "breaking", "fastball",
"fastball", "fastball",
"breaking", "fastball", "fastball",
"fastball", "fastball", "breaking",
"fastball", "breaking", "fastball",
"fastball", "breaking", "breaking",
"breaking", "breaking"))
)
ggplot()+
stat_density2d(data=oyaa,aes(x = plate_x, y = plate_z, fill = as.numeric(..level..)),
geom = "polygon", show.legend = FALSE, bins=30) +
geom_point(data=oyaa, aes(x = plate_x, y = plate_z, color=c(values=colors)), size=.95) +
xlab("plate_x")+ylab("plate_z")+xlim(-3,3)+ylim(0,5)+scale_fill_gradient2(mid="yellow",high = "red", midpoint = 0)+theme_classic()

colors <- c("deepskyblue1","darkolivegreen1","darkorchid2")
names(colors) = c("fastball", "offspeed", "breaking")

I am trying to give each fastball, offspeed, breaking from "pitch" a color.

I used scale_color_manual() to set the colors.

library(ggplot2)

oyaa <- data.frame(
  plate_x = c(-0.205, -0.017, -0.902, 0.229, -0.909, 0.903, 0.119, 0.787,
              -0.581, 0.913, 0.902, -0.881, -0.791,
              -0.943, -0.192, 0.912, -1.398, 0.383, -0.057,
              -0.487),
  plate_z = c(2.779, 3.339, 2.606, 1.678, 1.999, 3.689, 1.339, 2.881, 2.891,
              3.774, 2.441, 2.491, 2.488, 1.688, 2.388,
              3.981, 1.632, 2.879, 2.516, 2.798),
  pitch = as.factor(c("fastball", "fastball", "breaking", "fastball",
                      "fastball", "fastball",
                      "breaking", "fastball", "fastball",
                      "fastball", "fastball", "breaking",
                      "fastball", "breaking", "fastball",
                      "fastball", "breaking", "breaking",
                      "breaking", "breaking"))
)

Mycolors <- c("deepskyblue1","darkolivegreen1","darkorchid2")
names(Mycolors) = c("fastball", "offspeed", "breaking")

ggplot()+
  stat_density2d(data=oyaa,aes(x = plate_x, y = plate_z, fill = as.numeric(..level..)),
                 geom = "polygon", show.legend = FALSE, bins=30) +
  geom_point(data=oyaa, aes(x = plate_x, y = plate_z, color = pitch), size=.95) +
  xlab("plate_x")+ylab("plate_z")+xlim(-3,3)+ylim(0,5)+scale_fill_gradient2(mid="yellow",high = "red", midpoint = 0)+
  theme_classic() + scale_color_manual(values = Mycolors)
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.