I have some centroid positions which I would like to add to my existing ggplot but I am not sure how I could go about doing this. I have tried creating two ggplots and tried combining them but this did not seem to work out since my centroids do not have an E
value which resulted in Error in factor(E) : object 'E' not found
My goal is to have the data and the centroids appear all inside plot1 so we can see the data and the centroid positions.
CodePudding user response:
The main problem (and the reason for Error in factor(E) : object 'E' not found
is that the the criteria provided to your ggplot()
call get inherited to your later geom_point()
and geom_label()
. But since you there provide a new data =
, it cannot find the inherited E
.
So you can do as suggested by @Quinten or add inherit.aes = FALSE
, as in my solution.
Data
structure(list(Subject = 1:15, X = c(1L, 1L, 2L, 3L, 3L, 4L,
5L, 7L, 8L, 8L, 9L, 9L, 9L, 10L, 10L), Y = c(1L, 6L, 1L, 9L,
10L, 6L, 6L, 2L, 1L, 9L, 1L, 9L, 10L, 3L, 5L), E1 = c(1L, 1L,
NA, NA, NA, NA, 1L, 1L, 1L, 1L, NA, 1L, 1L, 1L, NA), E2 = c(NA,
NA, 2L, 2L, 2L, NA, NA, NA, NA, NA, 2L, NA, NA, NA, 2L)), class = "data.frame", row.names = c(NA,
-15L))
Code
library(dplyr)
library(ggplot)
data2 <- data %>% filter(!if_all(c(E1, E2), is.na)) %>% mutate(E = ifelse(is.na(E1), E2, E1))
x <- c(2,6.2, 8.8)
y <- c(3.5, 8.8, 2.4)
coords = paste(x , y, sep = ",")
df = data.frame(x, y)
ggplot(data2, aes(X, Y, shape = factor(E)))
geom_point(size = 4)
scale_shape_manual(values = c(8, 3), name = "E")
theme_bw()
geom_point(df, mapping = aes(x, y), col = "blue", size = 3, inherit.aes = FALSE)
geom_label(df, mapping = aes(x .5, y 0.5, label = coords), inherit.aes = FALSE)
Output