How to apply the coordinate limits to one layer only in ggplot?

Viewed 35

Data

The data files are not short enough for the question. You can download them here.

Problem

I have 2 datasets. The first one is the pos_df which contains the coordinates of vehicle motion as follows:

> head(pos_df)
  frames    ED_x      ED_y
1   1442 31367.9 -3103.045
2   1443 31367.9 -3103.045
3   1444 31367.9 -3103.043
4   1445 31367.9 -3103.041
5   1446 31367.9 -3103.038
6   1447 31367.9 -3103.034

I can plot it:

library(ggplot2)
ggplot() + 
  geom_path(data = pos_df, mapping = aes(ED_x, ED_y))

enter image description here

The second dataset is actually a svg image, Springfield.svg. I can read it using the svgparser package:

# remotes::install_github('coolbutuseless/svgparser')
library(svgparser)
df <- svgparser::read_svg("Springfield.svg", obj_type = 'data.frame') 

I can plot it as well:

ggplot() + 
 geom_path(data = df,
            aes(x, y,
                group = interaction(elem_idx, path_idx)),
            color = "grey50")  

enter image description here

But it is upside down. Zooming in to the section where pos_df is relevant and rotating the plot:

ggplot() + 
  geom_path(data = df,
            aes(x, y,
                group = interaction(elem_idx, path_idx)),
            color = "grey50") +
  coord_cartesian(xlim = c(30000, 44000),
                  ylim = c(5000, -7000))  

enter image description here

I want to now combine the two datasets. But when I do, the pos_df is also flipped:

ggplot() + 
  geom_path(data = df,
            aes(x, y,
                group = interaction(elem_idx, path_idx)),
            color = "grey50") +
  coord_cartesian(xlim = c(30000, 44000),
                  ylim = c(5000, -7000)) +
  geom_path(data = pos_df, mapping = aes(ED_x, ED_y), color = "red")+
  theme_bw()  

enter image description here

How can apply the coord limits to the df only?

1 Answers

One simple solution is to use -ED_y:

ggplot() + 
  geom_path(data = df,
            aes(x, y,
                group = interaction(elem_idx, path_idx)),
            color = "grey50") +
  coord_cartesian(xlim = c(30000, 44000),
                  ylim = c(5000, -7000)) +
  geom_path(data = pos_df, mapping = aes(ED_x, -ED_y), color = "red")+
  theme_bw() 

enter image description here

Related