【问题标题】:Plot some points in contour curve from ggplot2从ggplot2绘制轮廓曲线中的一些点
【发布时间】:2019-12-28 14:22:52
【问题描述】:

我想在等高线曲线中绘制特定数量的z 点,例如 8 或 10 个点。下面我展示了一个示例,但包含所有要点。

library(ggplot2)
library(tidyverse)

rosenbrock <- function(x){
    d <- length(x)
    out <- 0
    for(i in 1 : (d - 1)){
        out <- out + 100 * ( x[i]^2 - x[i + 1] )^2 + (x[i] - 1)^2
    }
    out
}

set.seed(2020)
coord <- matrix(runif(2000, -100, 100), ncol = 2)
graph <- apply(coord, 1, rosenbrock)    

results <- data.frame(x = coord[, 1], y = coord[, 2], z = graph)
results <- results %>% arrange(desc(z))    

results %>% 
    ggplot(aes(x = x, y = y, z = z)) + 
        geom_point(aes(colour = z)) + 
        stat_density2d() +
        theme_light()

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以在最初绘制点时将 alpha 设置为零,然后过滤数据以包含您想要的点(这里,我只是随机抽样):

    results %>% 
        ggplot(aes(x = x, y = y, z = z)) + 
        geom_point(aes(colour = z), alpha=0) + 
        stat_density2d() +
        geom_point(data = sample_n(results, 10), aes(colour = z)) + 
        theme_light()
    

    【讨论】:

      猜你喜欢
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      相关资源
      最近更新 更多