【问题标题】:3-variables plotting heatmap ggplot23 变量绘制热图 ggplot2
【发布时间】:2016-05-05 12:37:46
【问题描述】:

我目前正在处理一个非常简单的data.frame,包含三列:

x 包含一组点的 x 坐标,

y 包含点集的 y 坐标,并且

weight 包含与每个点关联的值;

现在,在ggplot2 工作,我似乎能够为这些数据绘制等高线水平,但我无法根据变量weight 找到填充绘图的方法。这是我使用的代码:

ggplot(df, aes(x,y, fill=weight)) + 
  geom_density_2d() +
  coord_fixed(ratio = 1) 

遗憾的是,您可以看到没有任何填充物。 我已经尝试了三天了,我开始感到沮丧。

在一般的ggplot 调用中指定fill=weight 和/或color = weight,没有任何结果。我尝试使用不同的几何图形(平铺、光栅、多边形......),但仍然没有。试图将aes直接指定到geom层,也没有成功。 试图将对象转换为 ppp,但 ggplot 无法处理它们,并且使用 base-R 绘图也不起作用。老实说,我不知道出了什么问题! 我附上了前 10 个点的数据,这些数据分布在不规则的网格上:

x = c(-0.13397460,-0.31698730,-0.13397460,0.13397460,-0.28867513,-0.13397460,-0.31698730,-0.13397460,-0.28867513,-0.26794919)

y = c(-0.5000000,-0.6830127,-0.5000000,-0.2320508,-0.6547005,-0.5000000,-0.6830127,-0.5000000,-0.6547005,0.0000000)

weight = c(4.799250e-01,5.500250e-01,4.799250e-01,-2.130287e+12,5.798250e-01,4.799250e-01,5.500250e-01,4.799250e-01,5.798250e-01,6.618956e-01)

有什么建议吗?期望的输出是这样的:

click

提前谢谢你。

【问题讨论】:

  • 听起来你在滥用密度图。密度图旨在估计潜在的概率密度函数(在样本空间上积分为 1 的函数)。也许听起来您想要某种形式的插值来将函数值散布到表面上?但在这种情况下,您需要为插值选择某种形式的统计建模。
  • 您是否尝试过查看filled.contour 函数?您首先需要使用library(akima)int.ds <- interp(df$x,df$y,df$weight,duplicate="strip") 之类的内容插入数据。然后你可以按照filled.contour(int.ds) 的方式做一些事情

标签: r plot ggplot2 heatmap density-plot


【解决方案1】:

根据您的描述,geom_density 听起来不太对。

你可以试试geom_raster:

ggplot(df, aes(x,y, fill = weight)) + 
     geom_raster() +
     coord_fixed(ratio = 1)  + 
     scale_fill_gradientn(colours = rev(rainbow(7)) # colourmap

【讨论】:

    【解决方案2】:

    这是使用fill=..level.. 的次优方法。 There is a good explanation on ..level.. here.

    # load libraries
      library(ggplot2)
      library(RColorBrewer)
      library(ggthemes)
    
    # build your data.frame
     df <- data.frame(x=x, y=y, weight=weight)
    
    # build color Palette
      myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")), space="Lab")
    
    
    # Plot
      ggplot(df, aes(x,y, fill=..level..) ) + 
          stat_density_2d( bins=11, geom = "polygon") +
          scale_fill_gradientn(colours = myPalette(11)) +
          theme_minimal() +
          coord_fixed(ratio = 1)
    

    【讨论】:

    • 这不使用权重。
    • 嗨@Axeman,你是对的。我的回答没有使用fill=weights,这就是为什么我说它是“第二好的”。据我所知,不可能将数据向量传递给stat_density_2d 中的fill。在Link我的回答中做了一些解释。
    猜你喜欢
    • 2022-11-02
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多