0

I want to compare different peaks from histograms, so I put two of them into one plot with alpha=0.5. The default output in RStudio looks fine, but when I use pdf() or ggsave() or even CairoPDF() the resulting output has solid lines around the boxes. In my case these solid lines sometimes look very ugly when zooming the pdf display. I want to disable these solid lines or at least have the lines to be the same color/alpha as the filling.

Minimal Code Example:

library(ggplot2)

p1<-ggplot()+
  geom_histogram(data=diamonds[diamonds$cut == "Premium",],aes(x=depth,fill=cut),alpha=0.5)+
  geom_histogram(data=diamonds[diamonds$cut == "Ideal",],aes(x=depth,fill=cut),alpha=0.5)

ggsave("histoline.pdf",p1)

this is the output:

enter image description here

I have tried various ways to modify linetypes and sizes but have not succeeded until now.

luchonacho
  • 6,759
  • 4
  • 35
  • 52
fulz
  • 41
  • 8
  • Have you tried [size](https://stackoverflow.com/questions/34878848/control-bar-border-color-thickness-with-ggplot2-stroke)? – Roman Luštrik Jul 28 '17 at 06:58
  • Same result for size=0, no Output for size=-1 and size=NA =( – fulz Jul 28 '17 at 07:12
  • linetype="blank" doesn't work for me either – fulz Jul 28 '17 at 07:20
  • hmmm, maybe the bars are overlapping a tiny bit? – fulz Jul 28 '17 at 10:06
  • when I zoom in to 6400% a gap becomes visible – fulz Jul 28 '17 at 10:12
  • I think the bins are overlapping a tiny bit. I did post this to the [ggplot2 mailing list](https://groups.google.com/forum/?fromgroups#!topic/ggplot2/-qKNaeT-Hns). Maybe there is a cleaner way to set bin positions? I don't know how ggplot handles pdf output. – fulz Jul 31 '17 at 06:24

1 Answers1

-1

A workaround is to compute the histogram manually and use ggplot to display the corresponding polygon only. It looks like what I want, but of course thats some extra lines of code and you lose a lot of ggplot functionality. Note: hist() and geom_hist() treat bin widths a little differently.

library(ggplot2)


hP <-hist(diamonds[diamonds$cut == "Premium",]$depth,breaks=seq(43,68,1))
hPd<-data.frame(breaks=c(hP$breaks[-1],hP$breaks),counts=c(hP$counts,hP$counts,hP$counts[1]))
hPd<-hPd[order(hPd$breaks),]

hI <- hist(diamonds[diamonds$cut == "Ideal",]$depth,breaks=seq(43,68,1))
hId<-data.frame(breaks=c(hI$breaks[-1],hI$breaks),counts=c(hI$counts,hI$counts,hI$counts[1]))
hId<-hId[order(hId$breaks),]

p1<-ggplot()+
  geom_polygon(data=hPd,aes(x=breaks,y=counts),fill="blue",alpha=0.5)+
  geom_polygon(data=hId,aes(x=breaks,y=counts),fill="red",alpha=0.5)
  #  this should yield the same binning behaviour as hist()
  #  geom_histogram(data=diamonds[diamonds$cut == "Premium",]
                  #,aes(x=depth),fill="green",binwidth=1,center=0.5,alpha=0.5)

print(p1)

ggsave("histoline.pdf",p1)
fulz
  • 41
  • 8
  • lets call it a work around. It looks like what I want to have, but the way there is not very elegant – fulz Jul 28 '17 at 11:43