RyanStochastic
RyanStochastic

Reputation: 4083

how to remove line from fill scale legend using geom_vline and geom_histogram r ggplot2

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')

enter image description here Edit: added image

Cheers, Ryan

Upvotes: 4

Views: 1940

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98509

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')

enter image description here

Upvotes: 3

Related Questions