【问题标题】:How to add an ellipse to a scatter plot colored by density in R?如何在R中按密度着色的散点图中添加椭圆?
【发布时间】:2021-06-16 17:20:39
【问题描述】:

我有一个代码可以生成一个按密度着色的散点图(灵感来自这篇帖子R Scatter Plot: symbol color represents number of overlapping points):

## Data in a data.frame
x1 <- rnorm(n=1000, sd=2)
x2 <- x1*1.2 + rnorm(n=1000, sd=2)
df <- data.frame(x1,x2)

## Use densCols() output to get density at each point
x <- densCols(x1,x2, colramp=colorRampPalette(c("black", "white")))
df$dens <- col2rgb(x)[1,] + 1L

## Map densities to colors
cols <-  colorRampPalette(c("#FF3100", "#FF9400", "#FCFF00", 
                            "#45FE4F", "#00FEFF", "#000099"))(6)
df$col <- ifelse(df$dens >= 250, cols[1], ifelse(df$dens >= 200, cols[2], ifelse(df$dens >= 150, cols[3], ifelse(df$dens >= 100, cols[4], ifelse(df$dens >= 50, cols[5], cols[6])))))

## Plot it, reordering rows so that densest points are plotted on top
plot(x2~x1, data=df[order(df$dens),], pch=20, col=col, cex=2)

我想添加一个椭圆,其中密度值等于一个固定值,例如 200。正是like in this image,其中绘制了一个椭圆,其中密度值等于 0.7。我没有生成此图像中的情节的代码,所以我真的不知道如何获得类似的东西

有人可以帮忙吗?

【问题讨论】:

    标签: r plot scatter-plot ellipse


    【解决方案1】:

    ggplot2 有一个学习曲线,但如果你愿意尝试一下,你可以使用 geom_density_2d。我认为它可以满足您的需求,至少在大多数情况下如此。

    https://ggplot2.tidyverse.org/reference/geom_density_2d.html

    【讨论】:

    • 是的,确实,我看到 ggplot2 是可能的,但我想在没有它的情况下这样做,就像我展示的图片一样。如果我没有找到任何其他解决方案,我会尝试使用此选项,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-11
    • 2018-01-07
    • 2015-04-03
    • 2013-12-05
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    相关资源
    最近更新 更多