1

I wish to add a colorbar to a scatterplot. Currently a discrete legend is generated that needs to be modified to colorbar. Please help me with this. Thanks in advance,

library(ggplot2)    
x_axis<-sample(1:55)
y_axis<-sample(100:154)

plotName<-'Scatter plot with colorbar instead of discrete legend'
color_plate <- colorRampPalette(colors = c('dodgerblue4','dodgerblue','green3','green2','yellow2','red','darkred'),space='Lab') #v1
color_plate <- color_plate(55) 


  dat_1 <- data.frame(xvar = x_axis, 
             yvar = y_axis,

col1 <- c(rep(1,8),rep(2,8),rep(3,8),rep(4,8),rep(5,8),rep(6,8),rep(7,7)))              
# col1<-(rep(1,6),rep(2,6),rep(3,6),rep(4,6),rep(5,6),rep(6,6),rep(7,6),rep(8,6),rep(9,7))) 
chart<-ggplot(dat_1, aes(x=xvar, y=yvar)) +
         geom_point(shape=19,size=5,aes(colour = col1)) +

 scale_colour_continuous( low = "blue", high = "red", space ="Lab",name="observation",label=rep("",7) , #nrow(dat_1)
 guide = guide_legend(direction = "horizontal", title.position = "bottom",     title.hjust=0.5) ) +

         theme(legend.position = "bottom") +
         labs(title=plotName)+
         scale_y_continuous(expression(atop('Net'~CO[2]~'Flux '~CO[2]~' (β)' )))+   
         scale_x_continuous(expression(atop('Gross'~CO[2]))) 

print(chart)    
4

1 回答 1

3

如果我们知道您选择这些特定颜色的原因,这会更容易。如果它们本质上是任意的,那么也许这会起作用:

### add a column for color
dat_1 <- data.frame(xvar = x_axis, 
                  yvar = y_axis,
                  col1 = 1:7)

编辑这应该接近你想要的

ggplot(dat_1, aes(x=xvar, y=yvar)) +
 geom_point(shape=19, size=5, aes(colour = col1)) +
 scale_colour_continuous( low = "blue", high = "red", space = "Lab",
  name="observation", label=rep("", nrow(dat_1)) ,
  guide = guide_legend(direction = "horizontal", 
   title.position = "bottom",     title.hjust=0.5) ) +
 theme(legend.position = "bottom")  +
 scale_y_continuous(expression(atop('Net'~CO[2]~'Flux '~CO[2]~' (β)' ))) +   
 scale_x_continuous(expression(atop('Gross'~CO[2]))) 

这使

在此处输入图像描述

根据您的评论,我通过""作为值传递使标签“空白”。更改外观遵循指南图例的帮助。如果您有 55 个观察值并希望它们都具有 7 个颜色值之一,那么:

dat_1$col1 <- rep(seq(7), 8)[-7*8]

应该为你做。您可以更改颜色以适合您的口味。我scale_color_brewer 个人喜欢,因为很容易看出哪些适合色盲观众。

更新2

我认为您的代码中可能存在拼写错误。以下对我有用:

set.seed(1)
dat_1 <- data.frame(xvar = sample(1:55),
                    yvar = sample(100:154),
                    col1 = c(seq(10), rep(seq(15), each=3))
                    )

然后如上图,你将有 55 个点,颜色为 15 种色调。

于 2013-09-23T18:56:40.510 回答