首页 > 解决方案 > 在 ggplot2 上显示水平误差线(带箭头?),即使它们超过 x 轴限制

问题描述

我是 R 的初学者。我希望误差条 (geom_errorbarh) 显示在绘图上,即使它们超过 x 轴限制。也许有一些迹象表明他们正在像箭头一样继续情节?我不想为少数异常值误差条扩展 x 轴限制,因为大部分绘图将被压扁到左侧。

data<-data.frame(index=c(1,2,3,1,2,3), 
    estimate=c("Network Estimate", "Indirect Estimate", "Direct Estimate",
               "Network Estimate", "Indirect Estimate", "Direct Estimate"),
    RR=c(1.15,2.2,1.12,1.84,1.21,2.73),
    ci_l=c(0.5,0.98,0.64,0.87,0.36,1.11),
    ci_u=c(2.44,12.09,1.97,1.9,2.8,11.72),
    Comparison=c("Example 2", "Example 2", "Example 2", 
                 "Example 1", "Example 1", "Example 1"))

xname<-"Relative Risk"

p <- ggplot(data, aes(y=index, x=RR, xmin=ci_l, xmax=ci_u))+ 
 geom_point()+ 
 geom_point(data=subset(data, Comparison=="All"), color="Black", size=2)+ 
 geom_errorbarh(height=.1)+
 scale_x_continuous(limits=c(0,3.5), breaks = c(0:3), name=xname)+
 scale_y_continuous(name = "", breaks=1:6, labels =data$estimate)+
 geom_vline(xintercept=1, color="black", linetype="dashed", alpha=.5)+
 facet_grid(Comparison~., scales= "free", space="free") +
 theme_grey()+
 theme(text=element_text(family="Times",size=14, color="black"))+
 theme(panel.spacing = unit(1, "lines"))+
 theme(strip.text.y = element_text(angle=0))

p

绘制缺少 2 个数据点的误差线

标签: rggplot2

解决方案


这回答了你的问题了吗?

ggplot(data, aes(y=index, x=RR, xmin=ci_l, xmax=ci_u))+ 
  geom_point()+ 
  geom_point(data=subset(data, Comparison=="All"), color="Black", size=2)+ 
  geom_errorbarh(height=.1)+
  scale_x_continuous(breaks = c(0:3),
                     #removed this
                     #limits = c(0, 3.5),
                     name = xname) +
  #added this
  coord_cartesian(xlim = c(0, 3.5)) +
  geom_segment(
    data = data %>% filter(Comparison == "Example 1"),
    x = 3.6, y = 3,
    xend = 3.65, yend = 3,
    lineend = "round",
    linejoin = "round",
    size = 0.5,
    arrow = arrow(length = unit(0.3, "cm"))) +
  geom_segment(
    data = data %>% filter(Comparison == "Example 2"),
    x = 3.6, y = 2,
    xend = 3.65, yend = 2,
    lineend = "round",
    linejoin = "round",
    size = 0.5,
    arrow = arrow(length = unit(0.3, "cm"))) +
  scale_y_continuous(name = "", breaks=1:6, labels =data$estimate)+
  geom_vline(xintercept=1, color="black", linetype="dashed", alpha=.5)+
  facet_grid(Comparison~., scales= "free", space="free") +
  theme_grey()+
  theme(text=element_text(family="Times",size=14, color="black"))+
  theme(panel.spacing = unit(1, "lines"))+
  theme(strip.text.y = element_text(angle=0))

推荐阅读