【问题标题】:How to create a heatmap with continuous scale using ggplot2 in R如何在 R 中使用 ggplot2 创建具有连续比例的热图
【发布时间】:2017-06-15 21:13:48
【问题描述】:

我有一个包含 1000 行的数据框,格式为

group = c("gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr3","gr3","gr3","gr3","gr3","gr3","gr3","gr3","gr3","gr3")
pos = c(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10)
color = c(2,2,2,2,3,3,2,2,3,2,1,2,2,2,1,1,1,1,1,1,2,2,2,2,2,2,1,1,2,2)
df = data.frame(group, pos, color)

并且想制作一种热图,其中一个轴具有连续的比例(位置)。颜色列是分类的。但是由于我想使用分箱的大量数据点,即将它用作连续变量。

这或多或少的情节应该是这样的:

我想不出使用 ggplot2/R 创建这样一个情节的方法。我尝试了几种几何形状,例如geom_point()

ggplot(data=df, aes(x=strain, y=pos, color=color)) + 
  geom_point() +
  scale_colour_gradientn(colors=c("yellow", "black", "orange"))

提前感谢您的帮助。

【问题讨论】:

  • 您的图片看起来更像是堆叠的条形图,而不是热图。不管怎样,你试过什么?
  • 我知道,但我无法使用 geom_bar()。
  • 不会像ggplot(df)+geom_tile(aes(x=group,y=pos,fill=as.factor(color))) 这样的工作吗?
  • 你也可以试试:ggplot(data=df, aes(x=group, y=pos, fill=factor(color))) + geom_bar(stat="identity")

标签: r plot ggplot2


【解决方案1】:

这对您有帮助吗?

library(ggplot2)
group = c("gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr1","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr2","gr3","gr3","gr3","gr3","gr3","gr3","gr3","gr3","gr3","gr3")
pos = c(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10)
color = c(2,2,2,2,3,3,2,2,3,2,1,2,2,2,1,1,1,1,1,1,2,2,2,2,2,2,1,1,2,2)
df = data.frame(group, pos, color)
ggplot(data = df, aes(x = group, y = pos)) + geom_tile(aes(fill = color)) 

看起来像这样

如果您喜欢,可以使用 3 种颜色渐变的改进版

library(scales)
ggplot(data = df, aes(x = group, y = pos)) + geom_tile(aes(fill = color))+ scale_fill_gradientn(colours=c("orange","black","yellow"),values=rescale(c(1, 2, 3)),guide="colorbar")

【讨论】:

  • 图书馆(规模)而不是图书馆(规模)
  • 感谢您的快速回复。当我使用 20000 而不是每组 10 个数据点时,绘制的线条会非常细。有没有让它更流畅?是否可以重命名颜色图例的刻度(例如 3.0 => 好、2.0 => 好、1.0 => 坏)并删除其他刻度?
  • 你能把整个数据上传到某个地方,这样我就可以使用它并向你发送更好的解决方案
猜你喜欢
  • 2012-07-16
  • 1970-01-01
  • 2017-10-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 2021-12-27
相关资源
最近更新 更多