我想创建扇区,然后为它们着色,这些代码确实如此,但我还想添加一个图例来表示从提供的色调中选择的颜色范围。它使用colour.heat和vector中的颜色,颜色总是在0和1之间,作为它的比例。
circs <- function(radii, sectors=4) {
radii <- sort(radii)
rads <- seq(0, 2*pi, length=2*length(radii)*sectors)# sample at these radians
do.call(rbind, lapply(radii, function(r) # points for drawing circles
data.frame(X=r*cos(rads), Y=r*sin(rads),
sector=rep(1:sectors, each=length(rads)/sectors),
theta=rads, radius=r)))
}
drawCirc <- function(radii, sectors, hues=NULL, densities=NULL, ...) {
polys <- circs(radii, sectors)
if (missing(hues)) {
colors <- colorRampPalette(c("green","yellow","red","blue"))(sectors*length(radii))
}
else
colors <- heat.colors(n=sectors*length(radii))
ind=0
plot(polys[,1:2], type="n" ,...) # blank plot
for (i in seq_along(radii)) { # add polygons
for (j in 1:sectors) {
ind <- ind+1
color <- colors[ind]
with(polys[polys$sector==j,],
if (i == 1) {
polygon(x=c(0, X[radius==radii[i]], 0), y=c(0, Y[radius==radii[i]], 0),
col=color, density=densities[ind])
} else
polygon(x=c(X[radius==radii[i-1]], rev(X[radius==radii[i]])),
y=c(Y[radius==radii[i-1]], rev(Y[radius==radii[i]])),
col=color, density=densities[ind]))
}
}
}
因此,当我运行以下代码时,它会绘制构成一个圆的扇区。
drawCirc(radii=1:50, sectors=24, hues=ration, main="Ratio by Colors")
ration = c( x_1,x_2... x_3600), where each x is between 0 and 1.
如何创建图例来表示颜色并将其添加到图表中?
我试过了,但遗憾的是无法添加图例。
答案 0 :(得分:0)
您可以在代码中函数drawCirc()
的最后添加以下行,就在关闭最后一个大括号之前:
nColors <-sectors*length(radii)
nLegend <- 5
legend("topleft",legend=c(formatC(rev(seq(0,1,1/(nLegend-1))),format="f",digits=2)), fill=c(colors[seq(0,nColors,nColors/nLegend)]))
鉴于您发布的代码的复杂性,我认为您根据需要难以适应和更改图例。
这是我获得的结果:
希望这有帮助。