首页 > 解决方案 > 使用带有 geom_point 和误差线的闪避来水平显示模型中的系数

问题描述

假设我有以下数据集

                                 term  estimate std.error statistic      p.value   conf.low conf.high  df                outcome model
                    outgroup_pairing1  9.173850  2.336151  3.926908 0.0001574491   4.539555 13.808145 101 outgroup_feelings_diff     1
                    outgroup_pairing1 11.663866  3.330378  3.502265 0.0006886152   5.057292 18.270440 101 outgroup_feelings_diff     2
 politicsRepublican:outgroup_pairing1 -5.002525  4.645316 -1.076897 0.2840919026 -14.217582  4.212531 101 outgroup_feelings_diff     2
                    outgroup_pairing1 10.657113  3.575874  2.980282 0.0036079930   3.563540 17.750686 101 outgroup_feelings_diff     3
 politicsRepublican:outgroup_pairing1 -4.928449  4.647266 -1.060505 0.2914443020 -14.147374  4.290476 101 outgroup_feelings_diff     3
                    outgroup_pairing1 10.512772  4.162351  2.525681 0.0131016794   2.255788 18.769757 101 outgroup_feelings_diff     4
 politicsRepublican:outgroup_pairing1 -5.359123  4.978743 -1.076401 0.2843123953 -15.235609  4.517363 101 outgroup_feelings_diff     4

我希望能够输出按型号分组的主效应和交互系数及其伴随的误差线。这是我最好的尝试:

ggplot(aes(x = estimate, y = model, color = term, group= term)) + 
geom_vline(xintercept = 0, linetype = 2) + 
geom_point(position="dodge") + 
geom_errorbarh(aes(xmin = conf.low, xmax = conf.high, height = 0.1),position="dodge") + 
ggtitle("Change in Outgroup Warmth") + 
geom_text(aes(label = paste("β = ", round(estimate, 2), "; p = ", round(p.value, 5)), vjust = -.5)) +
theme_bw() +  
theme(plot.title = element_text(hjust = 0.5)) +
ylab("Model")  +
xlab("Estimate")

但这会产生以下结果。

在此处输入图像描述

我希望系数水平“躲避”,这样它们就不会像那样重叠。我还希望删除图例中的“a”。

标签: rggplot2

解决方案


你不能在当前方向,躲避只在x方向有效。但是您可以反过来使用coord_flip和定义所有内容:

pos <- position_dodge(width = 0.5)
ggplot(df, aes(y = estimate, x = model, color = term, group= term)) + 
  geom_hline(yintercept = 0, linetype = 2) + 
  geom_point(position = pos) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high, width = 0.1), position = pos) + 
  ggtitle("Change in Outgroup Warmth") + 
  geom_text(aes(label = paste("β = ", round(estimate, 2), "; p = ", round(p.value, 5)), vjust = -.5),
            position = pos, show.legend = FALSE) +
  coord_flip() +
  theme_bw() +  
  theme(plot.title = element_text(hjust = 0.5)) +
  ylab("Model")  +
  xlab("Estimate")

在此处输入图像描述

另请注意show.legend = FALSE,您geom_text的图例中没有文本显示(“a”)。


推荐阅读