在ggplot2的y轴上插入自定义标签

时间:2019-04-18 14:30:23

标签: r ggplot2

我在R中使用ggplot2,试图插入一条红线来表示一条链的平均值。我想将平均值插入该行附近,这样就不必“扣除”该值。

我尝试对x使用负坐标,但是它不起作用,该值在轴的后面。

ggplot(data = chain.fmBC) + 
  geom_line(aes(1:25000, chain.fmBC$V2)) +
  labs(y = "", x = "") + 
  labs(caption= "Bayes C") + 
  geom_hline(yintercept = mean(chain.fmBC$V2), colour = "RED") +
  geom_text(label = round(mean(chain.fmBC$V2), 2), 
            x = 0, y = min(chain.fmBC$V2), colour = "RED")

这是我的图形的图片:

from https://i.imgur.com/hc0K9xh.jpg

如何将红色(媒体)值放在图的y轴左侧(介于0到5000之间),就像它是y轴的标签一样?

2 个答案:

答案 0 :(得分:0)

您可以手动设置y轴刻度,使其包含平均值。这将为您提供定位良好的注释。如果真正的问题是彩色轴标签,那么不幸的是,这并不能解决

示例:

ggplot(mtcars, aes(disp)) +
  geom_histogram() +
  geom_hline(yintercept = 0.5, color = "red") +
  scale_y_continuous(breaks = c(0,0.5,1,2,3,4)) +
  theme(axis.text.y = element_text())

哪个会给你这个:

img

答案 1 :(得分:0)

我很乐意分享我的建议。 我得到了很好的帮助here

cadeia.bayesc <- ggplot(data = chain.fmBC) + geom_line(aes(1:25000, chain.fmBC$V2)) +
        theme(plot.margin = unit(c(0.5,0.5,0.5,1), "lines")) +  # Make room for the grob
        labs(y = "", x = "") + labs(caption= "Bayes C") + 
cadeia.bayesc <- cadeia.bayesc + geom_hline(yintercept = mean(chain.fmBC$V2), colour = "RED") # insert the line

cadeia.bayesc <- cadeia.bayesc + annotation_custom( # grid::textgrob configure the label 
                grob = textGrob(label = round(mean(chain.fmBC$V2),2), hjust = 0, gp = gpar(cex = .7, col ="RED")),
                xmin = -6000, xmax = -100, ymin = mean(chain.fmBC$V2), ymax = mean(chain.fmBC$V2))

# Code to override clipping
cadeia.bayesc.plot <- ggplot_gtable(ggplot_build(cadeia.bayesc))
cadeia.bayesc.plot$layout$clip[cadeia.bayesc.plot$layout$name == "panel"] <- "off"
grid.draw(cadeia.bayesc.plot)

结果(https://i.imgur.com/ggbuNuK.jpg