1

I am trying to overlay a Plot and a Histogram in R, usign the ggplot2 package. The Plot contains a set of curves (visualized as straight lines due to logarithmich axis) and a horizontal line.

enter image description here

I would like to plot on the same image an histogram showing the density distribution of the crossing ponts between the curves and the horizontal line. I can plot the histogram alone but not on the graph because the aes-length is not the same (the last intersection is at x = 800, while the x asis is much longer).

the code I wrote is:

baseplot + 
geom_histogram(data = timesdf, aes(v)) + xlim(0,2000) 

where v contains the intersections between the curves and the dashed line.
Any ideas?

edited: as suggested I wrote a little reproducible example:

    library(ggplot2)

xvalues <- c(0:100)

yvalues1 <- xvalues^2-1000
yvalues2 <- xvalues^3-100
yvalues3 <- xvalues^4-10
yvalues4 <- xvalues^5-50

plotdf <- as.data.frame(xvalues)
plotdf$horiz <- 5
plotdf$vert1 <- yvalues1
plotdf$vert2 <- yvalues2
plotdf$vert3 <- yvalues3
plotdf$vert4 <- yvalues4

baseplot <- ggplot(data = plotdf, mapping = aes(x= xvalues, y= horiz))+
  geom_line(linetype = "dashed", size = 1)+
  geom_line(data = plotdf, mapping = aes(x= xvalues, y = vert1))+
  geom_line(data = plotdf, mapping = aes(x= xvalues, y = vert2))+
  geom_line(data = plotdf, mapping = aes(x= xvalues, y = vert3))+
  geom_line(data = plotdf, mapping = aes(x= xvalues, y = vert4))+
  coord_cartesian(xlim=c(0, 100), ylim=c(0, 1000))

baseplot

v<-c(ncol(plotdf)-1)
for(i in 1:ncol(plotdf)){
  v[i] <- plotdf[max(which(plotdf[,i]<5)),1]
}
v <- as.integer(v[-1])

timesdf <- as.data.frame(v)

# my wish: visualize baseplot and histplot on the same image
histplot <- ggplot() + geom_histogram(data = timesdf, aes(v)) + 
  coord_cartesian(xlim=c(0, 100), ylim=c(0, 10))
Frannzz
  • 103
  • 1
  • 3
  • 11
  • 1
    Can you please make your example reproducible (data for lines and raw values)? – Roman Luštrik Aug 03 '17 at 12:45
  • I would like to, but i shouldn't publish the actual code, which is also too long for the forum post. I am trying to write an example but it will take me some time. – Frannzz Aug 03 '17 at 12:58
  • You should publish enough code and data to reproduce your problem. If in doubt, you can always simulate data to mask anything sensitive. See [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for more info. – Roman Luštrik Aug 03 '17 at 13:00
  • ok, I wrote a reproducible example, the problem is the same but it has less lines. – Frannzz Aug 03 '17 at 13:28
  • 1
    What about plotting first the histogram and then adding all lines as `geom_line`? – S Rivero Aug 03 '17 at 13:40
  • I can try that, but I'm afraid it wouldn't work since the aesthetics have divverent lengths – Frannzz Aug 03 '17 at 14:25

0 Answers0