Benjamin
Benjamin

Reputation: 11860

ggplot gradientn fill based on data value with shape specified

In the ggplot2 example for scale_gradientn (second last graphic):

dsub <- subset(diamonds, x > 5 & x < 6 & y > 5 & y < 6) 
dsub$diff <- with(dsub, sqrt(abs(x-y))* sign(x-y)) 
(d <- qplot(x, y, data=dsub, colour=diff))

max_val <- max(abs(dsub$diff)) 
values <- seq(-max_val, max_val, length = 11) 
d + scale_colour_gradientn(colours = topo.colors(10), values = values, rescale = FALSE)

How can I fill according to a data value when using a "shape" symbol, i.e.:

(d <- qplot(x, y, data=dsub, fill=diff, colour="black", shape=21)) # Does not work

but with a black border and data-based fill rather than with a data-based border colour?

EDIT:

Proposed solutions are not quite working. All I need is to be able to use shape=21 with the example I show above, to get the same fill colour, but with a black border, i.e. this:

dsub <- subset(diamonds, x > 5 & x < 6 & y > 5 & y < 6) 
dsub$diff <- with(dsub, sqrt(abs(x-y))* sign(x-y))
max_val <- max(abs(dsub$diff))
values <- seq(-max_val, max_val, length = 11)

ggplot(dsub) +
    geom_point(aes(x=x,y=y, data=dsub, colour=diff), size=3) +
    scale_colour_gradientn(colours = topo.colors(10), values = values, rescale = FALSE)

but using shape=21 so that there is a black border and the fill is the same. This colours the outline, instead of the fill:

ggplot(dsub) +
    geom_point(aes(x=x,y=y, data=dsub, colour=diff), size=3, shape=21) +
    scale_colour_gradientn(colours = topo.colors(10), values = values, rescale = FALSE)

and this does not fill correctly:

ggplot(dsub) +
geom_point(aes(x=x,y=y, data=dsub, fill=diff), size=3, shape=21) +
scale_colour_gradientn(colours = topo.colors(10), values = values, rescale = FALSE)

Upvotes: 2

Views: 1822

Answers (2)

Benjamin
Benjamin

Reputation: 11860

As in the code shown by user1317221_G, the solution is to use scale_fill_gradientn, not scale_color_gradientn:

ggplot(dsub) +
    geom_point(aes(x=x,y=y,fill=diff), colour="black", size=3, shape=21) +
    scale_fill_gradientn(colours = topo.colors(10), values=values, rescale=FALSE)

Upvotes: 0

user1317221_G
user1317221_G

Reputation: 15461

using ggplot it would be:

d<-ggplot(dsub,aes(x=x,y=y,group=diff,fill=diff))
d+geom_point(colour="black",size=3,shape=21)

enter image description here

EDIT

d<-ggplot(dsub,aes(x=x,y=y,group=diff,fill=diff))
e<- d + geom_point(colour="black",size=3,shape=21)
e + scale_fill_gradientn(colours=topo.colors(10))

enter image description here

Also pretending that you have another layer somewhere e.g. geom_tile or something as you mentioned in your comment, here is an example with an extra geom_line layer which I have broken down into separate components to make it clear:

d<-ggplot(dsub,aes(x=x,y=y,group=diff,fill=diff))
e<-d+geom_line()
g<- e + geom_point(colour="black",size=3,shape=21)
g + scale_fill_gradientn(colours=topo.colors(10))

Upvotes: 1

Related Questions