how can I create an arrow or segment with gradient color using R?
Asked
Active
Viewed 2,157 times
2 Answers
7
I think Jim Lemon should be automagically bestowed 10K, maybe even 20K, rep points on SO just by virtue of all his work over the years creating base-graphics solutions. The guy is amazing. Time and again someone will ask for something on Rhelp, and he will whip up a solution. Here's "random rainbow" courtesy of the help page:
require(plotrix)
x<-c(0,cumsum(rnorm(99)))
y<-c(0,cumsum(rnorm(99)))
xydist<-sqrt(x*x+y*y)
plot(x,y,main="Random walk plot",xlab="X",ylab="Y",type="n")
color.scale.lines(x,y,c(1,1,0),0,c(0,1,1),colvar=xydist,lwd=2)

IRTFM
- 258,963
- 21
- 364
- 487
-
2Of course, the author of ggplot2's `qplot(x, y, colour=xydist, geom="path")` has his own fanclub too. – baptiste Jun 15 '12 at 22:23
-
@baptiste : , I'm a member of your fan club. Sadly I find a note that you ae no longer participating here. – IRTFM Jul 13 '22 at 14:13
6
Try this,
library(grid)
png("mask.png")
grid.polygon(c(-0.06, 0.06, 0.06, 0.15, 0, -0.15, -0.06),
c(-5, -5, 2.5, 2, 5, 2, 2.5), gp=gpar(fill="black"),
def="native",
vp=viewport(xs=c(-0.15, 0.15), ys=c(-5, 5)))
dev.off()
library(png)
m <- readPNG("mask.png", native=FALSE)
mask <- matrix(rgb(m[,,1],m[,,2],m[,,3]),
nrow=nrow(m))
rmat <- matrix(rgb(colorRamp(c("blue","white","red"))(seq(0,1,length=nrow(m))), maxColorValue=255),
nrow=nrow(m), ncol=ncol(m))
rmat[mask == "#FFFFFF"] <- NA
grid.newpage()
grid.raster(rmat)
Edit: you can reuse it in a plot, e.g.
library(ggplot2)
ggplot(iris) + geom_path(aes(Sepal.Length, Petal.Length, colour = Petal.Width)) +
guides(colour = guide_colourbar()) +
annotation_custom(rasterGrob(rmat, width=unit(1,"npc"), height=unit(1, "npc")),
x = 6, xmax=6.2, y=2.5, ymax=4)

baptiste
- 75,767
- 19
- 198
- 294
-
Great demonstration of building a mask and then coloring a png image with `colorRamp`. Could be used in lattice and as a stand alone object for pasting into other applications. – IRTFM Jun 16 '12 at 01:24