R: Color coding of scatterplot using ggplot

Asked 2 years ago, Updated 2 years ago, 87 views

I would like to create a scatterplot that is arbitrarily color-coded by the value of Reg when I use the following data Res.
US>Reg hw Sex
11 180 60 M
2 2 15550 F
3 316055F 42 170 65 M
...

base<-ggplot(Res,aes(x=h,y=w,colour=Reg))
points<-base+geom_point(size=5)
plot(points)

If it is run as it is, it will be color-coded by the Reg value, but
It is divided only by the shade of blue.
I'd like to make it more clear to display them in red, green, etc., but
How should I write it?please tell me。
Thank you for your cooperation.

r ggplot2

2022-09-30 19:23

2 Answers

Perhaps because the variable Reg used for color coding is treated as numerical data (continuous amount), it is color-coded as gradation.

Therefore, if you convert this variable to the factor type, you will be able to specify colors individually:

library(ggplot2)

## Create Descriptive Datas
Res<-data.frame(
  Reg=sample(1:3,50, replace=TRUE),
  h = rnorm (n = 50, mean = 165, sd = 10),
  w=rnorm (n=50, mean=55, sd=10)
)

## Color-coded variables into factor type
Res$Reg<-as.factor (Res$Reg)

## After that, the same description is OK.
base<-ggplot(Res,aes(x=h,y=w,colour=Reg))
points<-base+geom_point(size=5)
plot(points)

## Individual colors can also be specified

change_colors<-points+scale_colour_manual(values=c("red", "blue", "green")))
plot(change_colors)


2022-09-30 19:23

Res$Reg<-factor(Res$Reg)

If you don't like the color,

scale_color_manual(values=c("hoge", "hoge")))

and so on.


2022-09-30 19:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.