2012-05-02 6 views
2

Я стараюсь понять, добавить ли цветную метку к моему графику (link to previous question). Извините, что продолжайте спрашивать, но это максимум, я мог подтолкнуть меня вперед.цветная легенда ключа в r

#data 1: 
lab1 <- 1:10 
group <- rep(1:3, each = length (lab1)) 
label <- rep(lab1, 3) 
avar <- rep(c(0, 1, 4, 5, 6, 8, 10, 11, 12, 13), 3) 
myd <- data.frame (group, label, avar) 

# data 2 
fillcol <- rep(rnorm(length(lab1)-1, 0.5, 0.2), 3) 
group1 <- rep(1:3, each = length(fillcol)/3) 
# this variable will be used to fill color in bars 
filld <- data.frame(group1, fillcol) 


colbarplot <- function(group) { 

    myd1 <- myd[myd$group == group,] 
    filld1 <- filld[filld$group1 == group,] 
    blues <- colorRampPalette(c("yellow", "blue")) 
    barplot(as.matrix(diff(myd1$avar)), horiz=T, 
      col=blues(10)[10* filld1$fillcol], 
      axes=F, xlab="Mark") 
    axis(1, labels=myd$label, at=myd$avar) 
    axis(3, labels=myd$avar, at=myd$avar) 
} 

par(mfrow = c(4, 1)) 
par(mar = c(2.5, 1, 2.5, 1)) 
sapply(unique(myd$group),function(x) colbarplot(x)) 

Теперь я пытаюсь добавить легенду, извините за этого нового пользователя.

blues <- colorRampPalette(c("yellow", "blue")) 
    colors <- blues(10) 
    count <- length(colors) 
    m <- matrix(1:count, count, 1) 
    m1 <- m 
image(m, col=colors, ylab="", axes=FALSE) 

Я произвел цветовую гамму, что не то, что я ожидал, что я пытаюсь сюжет меньше легенды, меньше по высоте и ширине, наряду с оригинальным использованием шкалы в цветовой кодировке.

enter image description here

Вот некоторые неудачные испытания для маркировки:

colab <- c(round (min(filld$fillcol), 2), round(max(filld$fillcol), 2)) 
    colpos <- c(0.33 * max(mapdat$position),0.66 * max(mapdat$position)) 
    axis(1, labels=colab, at=colpos) 

ответ

3

Получение достойной легенды гораздо проще с ggplot2

library(plyr) 
myd$group <- factor(myd$group) 
gData <- ddply(myd, .(group), function(x){ 
    data.frame(delta = diff(x$avar), label = paste(head(x$label, -1), tail(x$label, -1), sep = "-")) 
}) 
gData$FillCol <- rnorm(nrow(gData)) 
ggplot(gData, aes(x = group, y = delta, fill = FillCol, label = label)) + geom_bar(stat = "identity") + coord_flip() + scale_fill_gradient(low = "blue", high = "yellow") + geom_text(position = "stack") 

ggplot2 graphic

+0

Спасибо Тьерри, я думаю, стоит изучить ggplot2. Единственная проблема, которую я хотел бы улучшить в плане, - это обозначить не 1-2 (интервал), а 1, 2, 3, как я и сделал. – shNIL

+0

Вы можете поместить любые метки, которые вам нравятся, с помощью geom_text(). – Thierry