为什么geom_hline在ggplot2中不生成图例? [英] Why doesn't geom_hline generate a legend in ggplot2?

查看:1512
本文介绍了为什么geom_hline在ggplot2中不生成图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码是绘制某些值的直方图,还有几条水平线代表参考点进行比较。但是,ggplot不会为这些行生成图例。

 图书馆(ggplot2)
图书馆(dplyr)

##将相同的混合对于[0,1]
x < - data.frame(PValue = c(runif(500),rbeta(500,0.25,1)))
y< - c(Uniform = 1,NullFraction = 0.5)%>%data.frame(Line = names(。)%>%factor(levels = unique(。)),Intercept =。)
ggplot +
aes(x = PValue,y = .. density ..)+ geom_histogram(binwidth = 0.02)+
geom_hline(aes(yintercept =截距,group = Line,color = Line,linetype = Line ),
data = y,alpha = 0.5)

我甚至尝试将问题只是画线:

  ggplot(y)+ 
geom_hline(aes(yintercept = Intercept,color = Line) )+ xlim(0,1)

我还没有看到图例。任何人都可以解释为什么我的代码不生成与传说的情节?

解决方案

默认 show_guide = FALSE 为 geom_hline 。如果您打开此功能,则会出现图例。此外,alpha需要位于 aes 内,否则线条的颜色将不会被正确绘制(在图例上)。代码如下所示:

  ggplot(x)+ 
aes(x = PValue,y = .. density ..)+ geom_histogram(binwidth = 0.02)+
geom_hline(aes(yintercept =截距,color = Line,linetype = Line,alpha = 0.5),
data = y,show_guide = TRUE)

并输出:


I have some code that is plots a histogram of some values, along with a few horizontal lines to represent reference points to compare against. However, ggplot is not generating a legend for the lines.

library(ggplot2)
library(dplyr)

## Siumlate an equal mix of uniform and non-uniform observations on [0,1]
x <- data.frame(PValue=c(runif(500), rbeta(500, 0.25, 1)))
y <- c(Uniform=1, NullFraction=0.5) %>% data.frame(Line=names(.) %>% factor(levels=unique(.)), Intercept=.)
ggplot(x) +
    aes(x=PValue, y=..density..) + geom_histogram(binwidth=0.02) +
    geom_hline(aes(yintercept=Intercept, group=Line, color=Line, linetype=Line),
               data=y, alpha=0.5)

I even tried reducing the problem to just plotting the lines:

ggplot(y) +
    geom_hline(aes(yintercept=Intercept, color=Line)) + xlim(0,1)

and I still don't get a legend. Can anyone explain why my code isn't producing plots with legends?

解决方案

By default show_guide = FALSE for geom_hline. If you turn this on then the legend will appear. Also, alpha needs to be inside of aes otherwise the colours of the lines will not be plotted properly (on the legend). The code looks like this:

ggplot(x) +
  aes(x=PValue, y=..density..) + geom_histogram(binwidth=0.02) +
  geom_hline(aes(yintercept=Intercept, colour=Line, linetype=Line, alpha=0.5),
             data=y, show_guide=TRUE) 

And output:

这篇关于为什么geom_hline在ggplot2中不生成图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆