how to remove line from fill scale legend using ge

2019-05-03 16:52发布

问题:

Basics: Using R statistical software, ggplot2, geom_vline, and geom_histogram to visualize some data. The issue is with the legend keys.

I'm trying to plot a pair of histograms from some stochastic simulations, and on top of that plot a couple of lines representing the result of a deterministic simulation. I've got the data plotted, but the legend keys for the histograms have an unnecessary black line through the middle of them. Can you help me remove those black lines? Some sample code reproducing the issue is here:

df1 <- data.frame(cond = factor( rep(c("A","B"), each=200) ), 
                 rating = c(rnorm(200),rnorm(200, mean=.8)))

df2 <- data.frame(x=c(.5,1),cond=factor(c("A","B")))

ggplot(df1, aes(x=rating, fill=cond)) + 
  geom_histogram(binwidth=.5, position="dodge") +
  geom_vline(data=df2,aes(xintercept=x,linetype=factor(cond)),
             show_guide=TRUE) +
  labs(fill='Stochastic',linetype='Deterministic')

Edit: added image

Cheers, Ryan

回答1:

One workaround is to change the order of geom_histogram() and geom_vline(). Then add another geom_vline() without aes(), just giving xintercept= and linetype=. This will not remove lines but will hide them under the color legend entries.

ggplot(data=df1, aes(x=rating, fill=cond)) + 
  geom_vline(data=df2,aes(xintercept=x,linetype=factor(cond)),
             show_guide=TRUE) +
  geom_histogram(binwidth=.5, position="dodge") +
  geom_vline(xintercep=df2$x,linetype=c(1,3))+
  labs(fill='Stochastic',linetype='Deterministic')