我使用火山数据(矩阵)绘制了填充的等高线。
filled.contour(volcano, color.palette = terrain.colors, asp = 0.5)现在,我想在绘图中添加一个点。这个点应该显示火山的最高点。可以在不使用ggplot2的情况下添加点吗?如果是,是如何实现的?
发布于 2019-03-30 05:22:41
我以为您可以找到最大值的位置并使用points()函数添加它,但这不起作用,因为绘图中显示的轴坐标与绘图用来放置绘图元素的内部坐标不同(有关详细信息,请参阅here )。
相反,您可以使用filled.contour的plot.axes参数在正确的位置获得最大值,正如here所解释的那样。我们还需要使用axis函数来绘制轴标记和标签,因为plot.axes参数覆盖了缺省轴。
# Get coordinates of maximum
max.point = (which(volcano==max(volcano), arr.ind=TRUE) - 1)/(dim(volcano) - 1)
# Use plot.axes argument to plot maximum point
filled.contour(volcano, color.palette = terrain.colors, asp = 0.5,
plot.axes={
points(max.point, col="red", pch=16)
axis(side=1)
axis(side=2)
}
)

作为参考,以下是在创建绘图后尝试添加点时发生的情况:
filled.contour(volcano, color.palette = terrain.colors, asp = 0.5)
points(max.point, col="red", pch=17)

这是一个ggplot2版本:
library(tidyverse)
cols = terrain.colors(3)
as.data.frame(t(volcano)) %>%
rownames_to_column(var="row") %>%
gather(col, value, -row) %>%
mutate(col=(as.numeric(gsub("V","",col)) - 1)/(nrow(volcano) - 1),
row=(as.numeric(row) - 1)/(ncol(volcano) - 1)) %>%
ggplot(aes(col, row, z=value)) +
geom_raster(aes(fill=value)) +
geom_contour(colour="grey50", size=0.2) +
geom_point(data=. %>% filter(value==max(value)),
colour="red", shape=16, size=2) +
coord_fixed(ratio = ncol(volcano)/nrow(volcano), expand=FALSE) +
scale_fill_gradient2(low=cols[1], mid=cols[2], high=cols[3],
midpoint=mean(volcano)) +
theme_minimal()

https://stackoverflow.com/questions/55425358
复制相似问题