在条形图RStudio中添加abline到图例

时间:2016-03-24 13:57:13

标签: r

barplot(counts, main="title",
      xlab=group, col=rainbow(20),
      legend = rownames(counts), 
      beside=TRUE, xlim=c(1,30))
abline(v=mean(df$ddd), col="red", lwd=2.5)

我的问题是 - 如何为传奇添加基线?我试图从barplot区域抛出传说并做一些事情,但它不起作用

1 个答案:

答案 0 :(得分:1)

如果不了解您的数据,很难准确复制您正在寻找的内容,但我认为您可能会发现R的ggplot2包非常有用:

library(ggplot2)

ggplot(data=iris) + geom_bar(aes(x=iris$Sepal.Length,fill=iris$Species)) +
      #Add abline - specifiy color aes so it appears in the legend
      geom_abline(aes(intercept=0,slope=1,color="Line description"),size=2.5,show_guide=TRUE) + 

      #Override the lines that would appear in "fill" portion of legend - the part of the legend that refers to species
      guides(fill = guide_legend(override.aes = list(linetype = 0), title="[TITLE OF FILL]"), 
             color = guide_legend(title="[TITLE OF LINE]")) + 

      #Change color of line to what you actually want
      scale_color_manual(values="#CC6666")

我们基本上“欺骗”ggplot将geom_abline放入图例中,然后从那里我们可以更改该行的标题,描述和颜色。

上面的代码告诉我们:

enter image description here