Reputation: 536
I am trying to plot lat long points on a plot using ggplot2 in R. The axes are lats on y and longs on x. I want a given location point to be the center of my plot and rest of the points on the scatter plot with respect to how far they are from this point (these points' lat long values are coming from a data frame). How can that particular point be at the center of it all? I tried making two separate geom_point layers and added the one point I want in the center first, and then added the second geom layer with the rest of the data. But it doesn't work. I also tried coord_fixed by using the lat long limits from the first geom layer when I only plotted the main center point on plot, but after adding second layer, it does not remain in the center. I also wonder why is there no function or attribute to set the center of the plot around a particular point, so that rest of the points can fall wherever on the plot, but the focus point is there where I want, but maybe it is too specific of a thing. Also, could the units on the axes be converted to meters?
Upvotes: 0
Views: 746
Reputation: 174586
The easiest way to do this is figure out what you want the range of your x axis to be, and the range that you want your y axis to be. Measure the distance along the x axis to the furthest point from your target point, and just make sure the x axis range is this big on both sides. Do the same for the y axis.
To demonstrate, I'll make a random sample of points with x and y co-ordinates, each made small and black:
set.seed(1234) # Makes this example reproducible
df <- data.frame(x = rnorm(200), y = rnorm(200), colour = "black", size = 1)
Now I'll choose one at random as my target point, making it big and red:
point_of_interest <- sample(200, 1)
df$colour[point_of_interest] <- "red"
df$size[point_of_interest] <- 5
So let's work out the furthest points North-South and East-West from our target and calculate a range which would include all points but have the target in the centre:
max_x_diff <- max(abs(df$x[point_of_interest] - df$x))
max_y_diff <- max(abs(df$y[point_of_interest] - df$y))
x_range <- df$x[point_of_interest] + c(-max_x_diff, max_x_diff)
y_range <- df$y[point_of_interest] + c(-max_y_diff, max_y_diff)
And now we just need to plot:
ggplot(df, aes(x, y, colour = colour, size = size)) +
geom_point() +
scale_colour_identity() +
lims(x = x_range, y = y_range) +
scale_size_identity() +
coord_equal()
We can see that even though our target is well off the center of the cluster, the target remains in the center of the plot.
With regards to changing latitude and longitude to meters, this requires a co-ordinate transformation. This has been answered many times on Stack Overflow and I won't duplicate those answers here. You could check out packages like rgdal
or perhaps SpatialEpi
which has the latlong2grid
function.
Upvotes: 2