简体   繁体   English

facet_grid中同一轴上的离散和连续比例

[英]discrete and continuous scales on same axis in facet_grid

I want to use facet_grid in ggplot2 to produce two graphs with continuous and discrete scales on the same axis - essentially my vector fac has a numeric part and a factor part. 我想用facet_gridggplot2产生两个图形与在同一轴线上连续和离散的尺度-实际上我的矢量fac有一个数字部分和要素的一部分。

toy=data.frame(type=xc("f f f f i i i i"),fac=c(letters[1:4],1:3,40))
ggplot(toy,aes(x=ifelse(type=="f",fac,as.numeric((fac)))))+
   geom_bar()+facet_grid(.~type,scales="free")

But it doesn't work because ggplot forces both scales to be discrete. 但它不起作用,因为ggplot强制两个尺度都是离散的。 在此输入图像描述

As you can see from the equal spacing of 1,2,3,40 on the right-hand plot. 正如您可以从右侧图上的1,2,3,40等间距看到的那样。

Two types of data in one column is not the best way to represent data. 一列中的两种类型的数据不是表示数据的最佳方式。

Changed sample data for column fac to get better representation. 更改了列fac样本数据以获得更好的表示。

toy=data.frame(type=c("f", "f","f", "f", "i", "i", "i", "i"),fac=c(letters[1:4],1,5,7,40))

To get an unequal spaces for numeric values you can make two geom_bar() call, each for separate type (using subset= ). 要获得数值的不等空格,可以进行两次geom_bar()调用,每次调用都是单独的类型(使用subset= )。 For letters use data as they are but for numeric data convert fac values to character and then to numeric. 对于字母,使用数据,但对于数字数据,将fac值转换为字符,然后转换为数字。 facet_grid() will ensure that you have two plots. facet_grid()将确保您有两个图。 scale_x_discrete() will work for both facets - you just have to provide desired breaks= values. scale_x_discrete()将适用于两个方面 - 您只需提供所需的breaks=值。

library(ggplot2)
library(plyr)    
ggplot(data=toy)+
  geom_bar(subset=.(type=="f"),aes(x=fac),width=0.2)+
  geom_bar(subset=.(type=="i"),aes(x=as.numeric(as.character(fac))))+
  facet_grid(.~type,scales="free") + 
  scale_x_discrete(breaks=c("a","b","c","d",1,5,7,40))

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM