r - 使用facet_wrap仅在某些子图中释放y轴

标签 r ggplot2 scale facet-wrap yaxis

我正在尝试使用facet_wrap在同一个图形中绘制三个不同的子图。我知道 y 轴可以通过 facet_wrap() 的参数 scales 来设置“自由”或“固定”。但是,由于我的数据的特征,我希望前两个图的 y 轴保持固定,但第三个图的 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, y = Metric)) + facet_wrap(facets = "Color", scales = "fixed")

如您所见,这两种选择都不是真正有用:如果我将比例设置为free,我就会失去GreenRed之间的比较,大致在相​​同的范围内。但是,如果我将它们设置为 fix,那么就不可能看到 Yellow 发生了什么。理想的情况是绿色红色处于相同的比例,黄色处于自己的比例。这可以用facet_wrap()来完成吗?

最佳答案

将此视为您的一个选项,但它使用 facetscales 包中的 facet_grid() 变体,允许您定义特定的比例。代码如下:

#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, 2700)),
  `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))

输出:

enter image description here

使用的一些数据:

#Data
Example <- structure(list(Color = c("Green", "Green", "Green", "Green", 
"Green", "Green", "Red", "Red", "Red", "Red", "Red", "Red", "Yellow", 
"Yellow", "Yellow", "Yellow", "Yellow", "Yellow"), Time = c(0L, 
2L, 4L, 6L, 8L, 10L, 0L, 2L, 4L, 6L, 8L, 10L, 0L, 2L, 4L, 6L, 
8L, 10L), Metric = c(200, 300, 600, 800, 1400, 2600, 150, 260, 
400, 450, 600, 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"))

关于r - 使用facet_wrap仅在某些子图中释放y轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64356677/

相关文章:

r - 将 geom_point 覆盖到 geom_bar。如何对齐点和条?

r - 如何将多个 fluidRows() 放在一个 Shiny 输出中?

r - 如何将 grobs 存储在列表中并将它们传递给 grobTree()?

r - 转换 Dataframe 以在 ggplot2 中制作瀑布图

r - 在barplot ggplot中手动设置每组颜色

android - 有没有什么办法可以使填充缩放到字体大小?

jquery Sprite 动画响应式

android 种植盒动画

r - 如何绘制一个因子的多个频率的数据框?

r - IBrokers需要历史 future 合约数据吗?