2015-04-24 30 views
0

以下是這個問題的一個例子,我有:在R,創建從數據幀2D圖(兩軸的值)

x <- c(1,1,1,2,2,2,3,3,3) 
y <- c('a','b','c','a','b','c','a','b','c') 
z <- c(2.5, 4.5, 6.5, 5.0, 3.0, 7.5, 1.0, 6.5, 2.0) 

fun <- data.frame(
    x = x, 
    y = y, 
    z = z 
) 

現在我已經創建了下面的數據幀稱爲fun

x y z 
1 1 a 2.5 
2 1 b 4.5 
3 1 c 6.5 
4 2 a 5.0 
5 2 b 3.0 
6 2 c 7.5 
7 3 a 1.0 
8 3 b 6.5 
9 3 c 2.0 

現在,我想要創建一個x軸爲(1,2,3),y軸爲(a,b,c),值(顏色)爲列z的值的2D圖。

有沒有簡單的方法來做到這一點?謝謝!

回答

1

你選擇在基地圖形

fun <- data.frame(
    x = c(1,1,1,2,2,2,3,3,3), 
    y = c('a','b','c','a','b','c','a','b','c'), 
    z = c(2.5, 4.5, 6.5, 5.0, 3.0, 7.5, 1.0, 6.5, 2.0) 
) 


zz <- with(fun, (z - min(z))/diff(range(z)) * 998) + 1 
par(mar = c(5,4,4,4)) 
with(fun, plot(x, y, pch = 19, cex = 2, 
       col = colorRampPalette(c('black','blue','lightblue'))(1000)[zz])) 

## adding a color bar 
plotr::color.bar(c('black','blue','lightblue'), 
       at.x = par('usr')[4] * 1.05, at.y = par('usr')[3]) 
with(fun, text(x = par('usr')[2] * 1.06, y = pretty(1:3), xpd = NA, pos = 4, 
       labels = pretty(fun$z, 3))) 

enter image description here

或網格

library('ggplot2') 
ggplot(data = fun, aes(x = x, y = y, colour = z)) + geom_point(size = 10) 

enter image description here

+0

嗨!我沒有意識到ggplot具有這樣簡單的功能。謝謝您的幫助! – xiaoxiao87

+0

@ xiaoxiao87對於自動圖例,特別是彩條,它很好。在基地中這樣做需要一些額外的工作,請參閱編輯。有第三方軟件包,一個彩色條功能,plotrix有我認爲 – rawr