R stat_contour incorrect polygon filling

When I use stat_contour with a polygon, some regions do not have to be filled, because there is no data there, I marked them in the figure. Does anyone know how to avoid this? In addition, there is a space between the axis and the area, how to remove it ?!

Here is the build code:

 plot_contour <- function (da, native ) { h2d<-hist2d(da$germ_div,da[[native]],nbins=40,show=F) h2d$counts<-h2d$counts+1 counts<-log(h2d$counts, base=10) rownames(counts)<-h2d$x colnames(counts)<-h2d$y counts<-melt(counts) names(counts)<-c('x','y','z') ggplot(counts,aes(x,y))+ stat_contour(expand=c(0,0),aes(z=z,fill=..level..),geom='polygon')+ stat_contour( data=counts[counts$x<=75,],aes(z=z,fill=..level..),bins=50,geom='polygon')+ scale_fill_gradientn(expand=c(0,0),colours=rainbow(1000), limits=c(log(2,base=10),4),na.value='white',guide=F)+ geom_contour(aes(z=z,colour=..level..),size=1.5)+ scale_color_gradientn(colours=rainbow(30),limits=c(log(2,base=10),4),na.value='white', guide=F) + theme_bw()+ scale_x_continuous(expand=c(0,0),limits=c(0,50))+ scale_y_continuous(expand=c(0,0),limits=c(40,100))+ labs(x=NULL, y=NULL, title=NULL)+ theme(axis.text.x = element_text(family='Times', colour="black", size=20, angle=NULL, hjust=NULL,vjust=NULL,face="plain"), axis.text.y = element_text( family='Times', colour="black", size=20,angle=NULL, hjust=NULL,vjust=NULL,face="plain") ) } da<-read.table('test.txt',header=T) i<-'test' plot_contour(da,i) 
+4
r polygon ggplot2
source share
2 answers

This did not match the comment, so post as an answer:

stat_contour does not handle polygons that are not well closed. In addition, there is a problem of accuracy that arises when setting up the bins manually, when the actual calculation of the contours can be frightening (this happens when the contour bins coincide with the graph data but are not recognized the same due to accuracy errors).

The first problem you can solve by expanding your grid by 1 around in each direction, and then setting each value in the matrix, which is less than the lowest, which you care about some kind of arbitrarily low value. This will force the calculation of the contour to close all polygons that would otherwise be open at the edges of the graph. Then you can set limits using coord_cartesian(xlim=c(...)) so that your axes merge with the chart.

The second problem I don’t know about is a good way to solve without changing the ggplot code. You cannot be affected by this problem.

+4
source share

@BrodieG Your answer is correct, but it is a bit complicated without any code.

Adding the following lines with the corresponding x, y values ​​(this is a better guess) makes things clearer:

  xlim(-10, 60)+ ylim(30, 120)+ coord_cartesian(xlim=c(0, 50),ylim=c(40, 100)) 
0
source share

All Articles