Home > Back-end >  How to apply the coordinate limits to one layer only in ggplot?
How to apply the coordinate limits to one layer only in ggplot?

Time:02-26

Data

The data files are not short enough for the question. You can download them 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?

CodePudding user response:

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