使用geom_text

问题描述

问题

我使用ggplot()程序包制作了图1(请参见下面的R代码),我的最终目标是将上下置信区间条的值分别标记为3个有效数字(如下表所示)。通过将这些标签与上下误差线对齐来进行绘制(请参见图3)。

我试图使用geom_text()处理代码(图2)(请参见下面的R代码);但是,我没有标记任何一个置信区间栏,而是意外地将错误的数字标签(不在我的数据表中)放置在每月的每个平均月点上。当我运行图2的代码时,背景网格和背景颜色也恢复了,我希望将图中的背景保持空白(图1 + 3)。

所需的输出

我想通过以相同的方式在表中标记关联的ci_low和ci_high值来生成类似于图3(请参见下文)的图。

如果有人可以帮助我解决这个问题,我将非常感激。

谢谢:)

表密钥:

  • ci_low =较低的置信区间
  • ci_high =较高的置信区间
  • S.E =标准错误
  • 平均月=每月平均观察次数
  • sd.Month =每月标准差

表格:

Merged_Blue_Whale_Summarised <- read.table(text = "
       Month Counts Mean.Month  sd.Month       S.E    ci_low    ci_hi
1    January    113   37.66667  5.686241  3.282953 31.232080 44.10125
2   February     94   31.33333  4.932883  2.848001 25.751251 36.91542
3      March    111   37.00000  5.291503  3.055050 31.012101 42.98790
4      April    111   37.00000 12.288206  7.094599 23.094586 50.90541
5        May     33   11.00000  7.937254  4.582576  2.018152 19.98185
6       July     16    8.00000  1.414214  1.000000  6.040000  9.96000
7     August     89   29.66667  9.291573  5.364492 19.152262 40.18107
8  September     86   28.66667 16.441817  9.492687 10.061000 47.27233
9    October     82   27.33333 12.503333  7.218803 13.184480 41.48219
10  November     81   27.00000 17.691806 10.214369  6.979837 47.02016
11  December    101   33.66667  4.041452  2.333333 29.093333 38.24000",header = TRUE)
# fix the month names order
Merged_Blue_Whale_Summarised$Month <- factor(Merged_Blue_Whale_Summarised$Month,levels = month.name)

R代码

library(ggplot2)

##Open a new window to plot the figure showing mean,and confidence intervals per month
dev.new()

####Code for plot 1

           p = ggplot(Merged_Blue_Whale_Summarised,aes(x=Month,y=Mean.Month,ymin=ci_low,ymax=ci_hi)) +
                      geom_line(aes(group=1),size=1) +
                      geom_errorbar(width=0.2,color="blue") + 
                      geom_point(size=2) + 
                      geom_label(aes(y=60,label=paste0("n=",Counts))) 
           
           p + theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank(),panel.background = element_blank(),axis.line = element_line(colour = "black"))
           
           ggsave("p.png",p)

p

##Code for plot 2

 p = ggplot(Merged_Blue_Whale_Summarised,ymax=ci_hi)) +
                  geom_line(aes(group=1),size=1) +
                  geom_errorbar(width=0.2,color="blue") + 
                  geom_point(size=2) + 
                  geom_label(aes(y=60,Counts))) 
       
       p + theme(panel.grid.major = element_blank(),axis.line = element_line(colour = "black"))
       
       p + geom_text(aes(label= sprintf("%.1f",ci_low,ci_hi),vjust=1.6,color="black",size=3.5))

       p

图1

enter image description here

图2

enter image description here

图3

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)