Creating a legend in r

I have a data set comprising a number of debris surveys around Australia. I wanted to aggregate these counts by grids of 10km by 10 km (approximately) and found a very useful post here: Aggregating points to grid using R

@whuber created a very clear way to graph the values, with the following code:

count.max <- max(counts.m["Count",])
colors = sapply(counts.m["Count",], function(n) hsv(sqrt(n/count.max), .7, .7, .5))
plot(counts.m["X",] + 1/2, counts.m["Y",] + 1/2, cex=sqrt(counts.m["Count",]/100),
pch = 19, col=colors,
xlab="Longitude of cell center", ylab="Latitude of cell center",
main="Event counts within one-degree grid cells")

Note that counts.m is a matrix with an X and Y value for the center points of the grids, and a statistic. In this case it is the total number of conflict events in Africa, but in my case it is the average amount of debris in a given grid.

I have re-created this code for my data set, but would now like to create a legend for the map. I've gotten as far as creating a fixed subset of boxes filled in with the appropriate colors, but can't get them to be circles or the appropriate size, as in the graph. Here is the code I have attempted thus far:

legend("topright", legend=c(1500,1000,500,25), pch=19,
pt.cex=sqrt(c(1500,1000,500,25)/100),
fill=sapply(c(1500,1000,500,25), function(n) hsv(sqrt(n/count.max), .7, .7, .5)))

Note that the original post (Aggregating points to grid using R) contains links to the data and code used to generate the count.max used above.

• One thing that sticks out; even though your point type is not changing, you still have to provide the same length for it to be replicated ie., pch=rep(19,4) – Jeffrey Evans Apr 19 '18 at 23:02
• Unfortunately that doesn't seem to help. I still have four colored boxes, and four dots of varying sizes, in black, superimposed on them. – Alexandra Apr 20 '18 at 3:14
• Oh, i did not catch that. Use col and not fill. – Jeffrey Evans Apr 20 '18 at 3:29