r - 如何使用小平面网格和位置闪避对绘图中的点范围进行排序和着色?

标签 r sorting ggplot2 colors facet

我有两组固定效应模型的多面网格图。在第一组中,我想抑制控制变量(显示为绿色)。在第二组中,如果模型中有一个带有 position_dodgev() 的控制变量,我想显示控制变量。

到目前为止我想通了这段代码:

library(ggplot2)
library(ggstance)
ggplot(mf, aes(fill=mn)) +
  geom_vline(xintercept=0) +
  geom_pointrangeh(aes(y=mn, x=coef, group=cv, color=cv, 
                       xmin=coef - se*1.96, xmax=coef + se*1.96),
                   position=position_dodgev(.5),
                   show.legend=FALSE) +
  scale_color_manual(values=c("green", "red", "green", "red")) +
  facet_grid(gr ~ ., scales="free", space="free")

这给了我这个:

enter image description here

然而,在模型 1 中,解释变量是重复的,并且组 2 模型中的解释变量并不总是在最前面。

我实际上想像这样看情节(经过照片处理):

enter image description here

ggplot() 怎么可能?


数据

mf <- structure(list(coef = c(3.025, 0.762499999999999, -1.44237073106609, 
-0.125042600081792, -0.689108910891089, 2.64264321029771, 2.64264321029771
), se = c(5.26319027539381, 3.34469904756018, 2.02098677878979, 
2.02098677878979, 2.02098677878979, 0.763989041657158, 0.763989041657158
), mn = structure(c(1L, 1L, 2L, 2L, 3L, 4L, 4L), .Label = c("Model 2c", 
"Model 2b", "Model 2a", "Model 1"), class = "factor"), gr = c(2, 
2, 2, 2, 2, 1, 1), cv = structure(c(2L, 1L, 2L, 3L, 2L, 2L, 3L
), .Label = c("gear", "vs", "disp"), class = "factor")), row.names = c("vs", 
"gear", "vs1", "disp", "1", "11", "2"), class = "data.frame")

最佳答案

对您的数据进行一些小的更改将有助于修正情节。首先,我们可以删除模型 1 的重复行。其次,您的 cv 颜色更改顺序的问题是模型 2a 和 2b 之间的控制变量不同。我们可以创建一个指示器列来简单说明该行是否是控制变量,并使用它来为绘图着色。

library(tidyverse)
library(ggstance)

mf %>% 
  #remove the dupe from Model 1
  filter(!(mn == "Model 1" & cv == "disp")) %>% 
  #create an indicator column for control variables
  mutate(Control = cv == "vs") %>% 
  ggplot(aes(fill=mn)) +
  geom_vline(xintercept=0) +
  #group and color using our new indicator variable
  geom_pointrangeh(aes(y=mn, x=coef, group=Control, color=Control, 
                       xmin=coef - se*1.96, xmax=coef + se*1.96),
                   position=position_dodgev(.5),
                   show.legend=FALSE) +
  scale_color_manual(values=c("green", "red", "green", "red")) +
  facet_grid(gr ~ ., scales="free", space="free")

final plot

关于r - 如何使用小平面网格和位置闪避对绘图中的点范围进行排序和着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53834382/

相关文章:

r - 在 R 中将时间转换为 'HMS"字符格式

javascript - 对数组进行排序,使特定项在数组中排在第一位

r - 如何添加水平线显示ggplot2中所有组的平均值?

r - ggplot2 : Add a gradient colored square according to values

r - 在 Shiny 中使用 Source()

regex - 如何在R中使用RegEx替换字符串中的字符

从数据框中删除 N/A

c - 将数组分成两部分,对每个部分进行排序,然后重新组合成单​​个数组

xml - 使用变量中的其他节点在 XSL apply-templates 节点中排序 (XSLT 1.0)

r - 如何根据方向制作具有不同颜色段的(ggplot)线图