问题描述
我正在尝试使用facet_wrap
在同一图形内绘制三个不同的子图。我知道y
轴可以使用scales
的参数facet_wrap()
来“自由”或“固定”设置。但是,由于我的数据的特性,我想将y
轴的前两个图保持不变,但将第三个图重新缩放。我可以做三个单独的图并将它们排列在一起,但是由于我在Shiny应用程序中使用此代码,所以这不是最方便的。在下面,您将找到到目前为止我的数据和代码的最小示例。
##Data example:
Color Time Metric
1 Green 0 200.00
2 Green 2 300.00
3 Green 4 600.00
4 Green 6 800.00
5 Green 8 1400.00
6 Green 10 2600.00
7 Red 0 150.00
8 Red 2 260.00
9 Red 4 400.00
10 Red 6 450.00
11 Red 8 600.00
12 Red 10 650.00
13 Yellow 0 0.10
14 Yellow 2 0.20
15 Yellow 4 0.30
16 Yellow 6 0.60
17 Yellow 8 0.55
18 Yellow 10 0.70
#With free scales
ggplot(Example) + geom_point(aes(x = Time,y = Metric)) + facet_wrap(facets = "Color",scales = "free")
#With fixed scales:
ggplot(Example) + geom_point(aes(x = Time,scales = "fixed")
如您所见,这两种选择都不是真正有用的:如果将比例尺设置为free
,则会丢失Green
和Red
之间的比较,它们之间的比较范围大致相同。但是,如果我将它们设置为fix
,则无法看到Yellow
发生了什么。理想的做法是使Green
和Red
具有相同的比例,而yellow
具有其自身的比例。可以使用facet_wrap()
吗?
解决方法
可以将其视为一个选项,但它使用软件包facet_grid()
中的facetscales
变体,它允许您定义特定的比例。这里的代码:
#Install
#devtools::install_github("zeehio/facetscales")
library(tidyverse)
library(facetscales)
#Define scales
scales_y <- list(
`Green` = scale_y_continuous(limits = c(0,2700)),`Red` = scale_y_continuous(limits = c(0,`Yellow` = scale_y_continuous(limits = c(0,0.7))
)
#Code
ggplot(Example) +
geom_point(aes(x = Time,y = Metric)) +
facet_grid_sc(Color~.,scales = list(y = scales_y))
输出:
使用了一些数据:
#Data
Example <- structure(list(Color = c("Green","Green","Red","Yellow","Yellow"),Time = c(0L,2L,4L,6L,8L,10L,0L,10L),Metric = c(200,300,600,800,1400,2600,150,260,400,450,650,0.1,0.2,0.3,0.6,0.55,0.7)),class = "data.frame",row.names = c("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18"))