在R中创建轮廓线或百分位线

时间:2016-01-12 10:45:21

标签: r graphics ggplot2 contour

我正在从这个矩阵创建以下等高线图。但是,我想要一个由我选择的轮廓线(没有填充轮廓)显示的图表,表示0.50(黑色)和0.25和0.75(红色)的值。 非常感谢有关该方法的帮助。

B = matrix(c(0.158,0.182,0.306,0.46,0.601,0.77,0.796,0.832,
             0.174,0.216,0.373,0.58,0.769,0.862,0.907,0.929,
             0.164,0.262,0.442,0.73,0.886,0.93,0.949,0.976,
             0.171,0.218,0.509,0.791,0.915,0.972,0.987,0.992,
             0.174,0.288,0.563,0.848,0.961,0.993,0.998,1,
             0.185,0.288,0.618,0.89,0.976,0.993,0.996,1,
             0.215,0.317,0.667,0.911,0.988,0.999,0.999,0.999,
             0.199,0.328,0.685,0.957,0.994,1,1,1,
             0.231,0.362,0.741,0.953,0.998,1,1,1,
             0.237,0.373,0.782,0.976,0.999,1,1,1,
             0.25,0.398,0.799,0.974,0.997,1,1,1,
             0.26,0.443,0.855,0.989,0.999,1,1,1,
             0.272,0.478,0.868,0.994,1,1,1,1,
             0.256,0.487,0.91,0.996,1,1,1,1,
             0.268,0.508,0.933,1,1,1,1,1),
             nrow=15, ncol=8,byrow=T) 


# Change column names
nv <- c(20,30,40,50,60,70,80,90,100,110,120,140,160,180,200)
location <- c(0,1,2,3,4,5,6,7) 
rownames(B) <- nv
colnames(B) <- location


# Create levels so they can be uniform accross all the images
b <- seq(0,1,0.05)

# Make levels that cover both ranges of z values
lvls <- pretty(range(b),20)

# Set up axis labels
matrix.axes <- function(data) {
        # Do the rows, las=2 for text perpendicular to the axis
        x <- (1:dim(data)[1] - 1) / (dim(data)[1] - 1);
        axis(side=1, at=x, labels=rownames(data), las=2);
        # Do the columns
        x <- (1:dim(data)[2] - 1) / (dim(data)[2] - 1);
        axis(side=2, at=x, labels=colnames(data), las=2);
}


filled.contour(B, plot.axes=matrix.axes(B),
               plot.title=title(main=paste("Graph"),
                                xlab='Sample number',ylab='Distance'),
               color.palette=colorRampPalette(c('white','blue','yellow','red','darkred')),
               levels=lvls)

enter image description here

上面的填充轮廓是我目前所拥有的,但是想要将其更改为图形,其中不同的轮廓线代表0.50(黑色)和0.25和0.75(红色)值(总共3行)。我正在标记ggplot2,因为那里可能有解决方案吗?

2 个答案:

答案 0 :(得分:1)

Use the contour function instead:

contour(B, levels = c(0.25, 0.5, 0.75), col = c(2, 1, 2), axes = F,
        xlab = 'Sample number', ylab = 'Distance')
axis(1, at = seq(0, 1, length= length(nv)), labels = nv)
axis(2, at = seq(0, 1, length= length(location)), labels = location)

enter image description here

答案 1 :(得分:0)

我设法很容易解决它!

contour(B,levels=c(0.5),lwd=3)
contour(B,levels=c(0.25,0.75), lwd=2, col = 34, add=TRUE)