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

南笙酒味 提交于 2021-02-20 02:16:39

问题


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

Package used: tidyverse

But I am getting the following error when using the 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:


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

# 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).



来源:https://stackoverflow.com/questions/51120067/how-to-zoom-in-on-a-specific-range-of-values-for-a-categorical-variable-in-ggplo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!