galtor
galtor

Reputation: 151

How can I make a scatterplot in R with different colours depending on the row?

I have the following dataset imported in RStudio

enter image description here

I would like to make a scatterplot where points of rows 1 to 3 are red and points of the rest of the rows are blue. How must I modify the code, please?

 plot(x=dataset$`col1`,y=dataset$col2, xlab="col1", ylab="col2",pch=16)

Upvotes: 0

Views: 452

Answers (3)

jay.sf
jay.sf

Reputation: 73692

More generally, you could initialize an empty plot and then points on corresponding subsets with the desired colors.

with(dataset, plot(col1, col2, xlab="col1", ylab="col2", type="n"))
with(dataset[1:3, ], points(col1, col2, pch=16, col="red"))
with(dataset[-(1:3), ], points(col1, col2, pch=16, col="blue"))

enter image description here


Data

dataset <- structure(list(col1 = 1:5, col2 = c(1, 1, 1, 1, 1)), class = "data.frame", row.names = c("a", 
"b", "c", "d", "e"))

Upvotes: 1

Yuriy Saraykin
Yuriy Saraykin

Reputation: 8880

additional option

library(tidyverse)
set.seed(0)
df <- tibble(
  col1 = runif(5),
  col2 = runif(5)
  ) %>% 
  mutate(grp = row_number()<= 3)

ggplot(df, aes(col1, col2, color = grp)) +
  geom_point() +
  scale_color_manual(values = c("red", "blue")) +
  theme(legend.position = "none")

Upvotes: 1

mnist
mnist

Reputation: 6954

In case you are happy with coloring the first 3 rows red, you can use this:

dataset <- data.frame(col1 = 1:5,
                      col2 = 1,
                      row.names = c("a", "b", "c", "d", "e"))


my_colors <- c(rep("red", 3), # first 3 red
               rep("blue", nrow(dataset) - 3)) # rest is blue
plot(x = dataset$col1,
     y = dataset$col2, 
     xlab = "col1", 
     ylab = "col2",
     pch = 16, 
     col = my_colors)

Upvotes: 1

Related Questions