How to zoom in on a specific range of values for a categorical variable in ggplot2?


How to zoom in on a specific range of values for a categorical variable in ggplot2?



I just want to zoom-in on the x axis between the values ford and nissan in the mpg dataframe.



packageused: tidyverse



But I am getting the following error when using coord_cartesian() function


p<-ggplot(mpg,aes(x=manufacturer,y=class))

p+geom_point()+ + coord_cartesian(xlim = c('ford','nissan'))



Error in +coord_cartesian(xlim = c("ford", "nissan")) : invalid
argument to unary operator




1 Answer
1



You can use a function for contextual zoom from ggforce package (facet_zoom) to achieve this:


ggforce


facet_zoom


# loading needed libraries
library(ggplot2)
library(ggforce)

# selecting variables to display
names <- as.vector(unique(mpg$manufacturer))
selected.names <- names[4:11]

# zooming in on the axes
ggplot(mpg, aes(x = manufacturer, y = class)) +
geom_jitter() +
facet_zoom(x = manufacturer %in% selected.names)





Created on 2018-07-01 by the reprex package (v0.2.0).





but this just zooms in on ford and nissan I want to zoom in from ford to nissan including all the values in between.
– Steve austin
Jul 1 at 17:11






@Steveaustin Updated the answer.
– Indrajeet Patil
Jul 1 at 17:49







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API