i am trying to create a figure which shows a spatially explicit system of nodes on a background grid. Here I have created a code which is lattice-like, but the shapes can vary so ideally the code would be working with any set of coordinates and adjacency matrices. The code works now, but the overlay of the nodes is not aligned to the grid, and i cannot manage to figure it out.
Here is some sample data and my code:
library(ggplot2)
library(igraph)
library(grid)
library(ggraph)
# Create a data frame with coordinates and values
coordinates <- matrix(c(1, 1, 2, 1, 3, 1, 0, 2, 1, 2, 2, 2, 3, 2, 0, 3, 1, 3, 2, 3, 3, 3), ncol = 2, byrow = TRUE)
colnames(coordinates) <- c("y", "x")
values <- c(22, 22, 20, 18, 21, 22, 21, 16, 22, 22, 21)
data <- data.frame(coordinates, value = values)
# Create adjacency matrix
adj_matrix <- matrix(c(0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0,
1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0,
1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0,
0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0,
0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1,
0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0,
0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0), nrow = 11, byrow = TRUE)
# Create graph from adjacency matrix
graph <- graph_from_adjacency_matrix(adj_matrix, mode = "undirected")
# Add coordinates and values as vertex attributes
V(graph)$x <- data$x
V(graph)$y <- data$y
V(graph)$value <- data$value
# Plot the graph with nodes colored based on values
#plot(graph, layout = as.matrix(data[, c("x", "y")]), vertex.color = colorRampPalette(c("lightgreen", "darkgreen"))(max(data$value) - min(data$value) + 1)[data$value - min(data$value) + 1], vertex.size = 15, edge.width = 1)
# Define breaks and limits for x and y axes
x_breaks <- seq(floor(min(data$x)), ceiling(max(data$x)), by = 1)
y_breaks <- seq(floor(min(data$y)), ceiling(max(data$y)), by = 1)
# Create empty grid
grid_plot <- ggplot() +
geom_blank(data = data, aes(x = x, y = y)) +
coord_cartesian(expand = FALSE, xlim = c(floor(min(data$x)), ceiling(max(data$x))), ylim = c(floor(min(data$y)), ceiling(max(data$y)))) +
theme_minimal() +
theme(panel.grid.major = element_line(colour = "grey", linetype = "dotted")) +
scale_x_continuous(breaks = x_breaks) +
scale_y_continuous(breaks = y_breaks)
# Create ggraph plot from igraph graph
ggraph_plot <- ggraph(graph, layout = "manual", x = V(graph)$x, y = V(graph)$y) +
geom_edge_link() +
geom_node_point(aes(color = value), size = 5) +
scale_color_gradient(low = "lightgreen", high = "darkgreen") +
theme_void()
# Combine ggplot grid and ggraph plot
combined_plot <- grid_plot + annotation_custom(ggplotGrob(ggraph_plot), xmin = floor(min(data$x)), xmax = ceiling(max(data$x)), ymin = floor(min(data$y)), ymax = ceiling(max(data$y)))
# Plot the combined grid and ggraph plot
grid.newpage()
print(combined_plot)
And here is the figure that it currently creates.
Thank you for considering this issue