I have a dataframe like this:
item <- c("item1", "item2", "item3", "item1", "item2", "item3", "item1", "item2", "item3")
group <- c("A", "B", "C", "A", "B", "C", "A", "B", "C")
level <- c(NA, NA, 40, NA, 25, NA, 30, NA, NA)
data <- cbind(item, group, level)
data <- as_tibble(data)
data <- type.convert(data, as.is = TRUE)
Which appears as follows:
item group level
item1 A NA
item2 B NA
item3 C 40
item1 A NA
item2 B 25
item3 C NA
item1 A 30
item2 B NA
item3 C NA
Every item is univocally associated to a specific group ( item1
is always linked to group A
, item2
always to group B
, etc.)
To plot the graph of the data, I use this code:
graph <- data %>%
ggplot(aes(x=group, y=level)) +
geom_point(colour="blue", size=3, na.rm=TRUE)
which shows this result:
Now, I would like to display in red the point with value 25
, selecting it by the item.
I.e., "if the item2
(which corresponds to group B
) has a value != NA, display its value in red, keeping all the other values in blue".
I have thought to a if
in a for-cycle
, but I don't know if it is the right reasoning.
Thank you for helping!
CLOSED: SOLUTION FOUND
I have created a subset of the dataframe by item:
my_dot <- subset(data, item=="item2")
my_dot <- type.convert(my_dot, as.is = TRUE)
and added a line to the ggplot which load the subsetted dataframe "my_plot" in geom_point(data=my_dot, ...)
graph <- data %>%
ggplot(aes(x=group, y=level)) +
geom_point(colour="blue", size=3, na.rm=TRUE) +
geom_point(data=my_dot, aes(x=group, y=level), colour="red", size=5, na.rm=TRUE)
Here the result I was looking for: