2D直方图的平均线?

时间:2017-06-29 22:50:25

标签: r

我是“R”的新用户并且有一个问题。我目前正致力于在R上制作2D直方图。材料必然无关紧要,但如何在2D直方图上绘制平均线。我正在运行的代码是:

load("mydatabin.RData")
# Color housekeeping
library(RColorBrewer)
rf <- colorRampPalette(rev(brewer.pal(11,'Spectral')))
r <- rf(32)

# Create normally distributed data for plotting
x <- mydata$AGE
y <- mydata$BP
df <- data.frame(x,y)

# Plot
plot(df, pch=16, col='black', cex=0.5)

这给了我一个散点图,然后把它变成我做的2D直方图:

library(ggplot2)

# Default call (as object)
p <- ggplot(df, aes(x,y))
h3 <- p + stat_bin2d()
h3

# Default call (using qplot)
qplot(x,y,data=df, geom='bin2d')

在此之后我做了:

h3 <- p + stat_bin2d(bins=25) + scale_fill_gradientn(colours=r)
h3

添加颜色。

因此,从这里我如何绘制数据的平均线。

如果有人能告诉我如何使用mydatebin.RData绘制看起来像这样的热图:

heat map plot

感谢。

1 个答案:

答案 0 :(得分:0)

您可以在geom_hline中使用geom_vlineggplot2,将y / xintercept作为参数传递以绘制线条。在您的情况下,参数可以是您绘制平均线的列的平均值。请参阅示例的代码。 我也玩过并尝试了两种不同的方法来绘制2D直方图。虽然我删除了colorBrewer,但你似乎更好,更精确。

library(ggplot2)

# Create normally distributed data for plotting
x <- rnorm(10000)
y <- rnorm(10000)
df <- data.frame(x,y)

# stat_density2d way, with average lines
p1 <- ggplot(df,aes(x=x,y=y))+
  stat_density2d(aes(fill=..level..), geom="polygon") +
  scale_fill_gradient(low="navy", high="yellow") +
  # Here go average lines
  geom_hline(yintercept = mean(df$y), color = "red") +
  geom_vline(xintercept = mean(df$x), color = "red") +
  # Just to remove grid and set background color
  theme(line = element_blank(),
        panel.background = element_rect(fill = "navy"))
p1

enter image description here

# stat_bin2d way, with average lines
p2  <- ggplot(df, aes(x,y)) +
  stat_bin2d(bins=50) +
  scale_fill_gradient(low="navy", high="yellow") +
  # Here go average lines
  geom_hline(yintercept = mean(df$y), color = "red") +
  geom_vline(xintercept = mean(df$x), color = "red") +
  # Just to remove grid and set background color
  theme(line = element_blank(),
        panel.background = element_rect(fill = "navy"))
p2

enter image description here