【问题标题】:R heatmap newbie: plot pair countsR热图新手:绘图对计数
【发布时间】:2016-01-12 12:02:59
【问题描述】:

我需要创建一个显示不同 (charCount, wordCount) 对计数的热图(其中charCount 是字符数,wordCount 是文本摘要中的单词数)。 作为输入,我有一个 csv 文件,其中每行有两个数字:charCountwordCount。我可以将其读入矩阵,然后绘制热图:

data = read.csv("chars_words.txt", sep=",", header=FALSE)
mtx <- as.matrix(data)
heatmap(mtx)

对于以下数据:

charCount, wordCount
1000,100
1000,100
1000,100
900,90
800,80
700,70
600,60
500,50
300,30
200,20
100,10​

我只得到了两种颜色的图。如何创建一个显示不同 (charCount, wordCount) 对计数和颜色的图?

*** 更新 2:

moto 的这段代码解决了我的问题:

library(ggplot2)
library(dplyr)

# Convert your data into frequency matrix, then data.frame
df<-data.frame(table(data))

# Set columns ready for ggplot
df$Freq<-as.factor(df$Freq)
df$charCount<-as.character(df$charCount) %>% as.numeric()
df$wordCount<-as.character(df$wordCount) %>% as.numeric()

# plot using ggplot
ggplot(df,aes(x=charCount,y=wordCount)) +
geom_tile(aes(fill=Freq)) +
geom_text(aes(label=Freq))

这导致了一个很好的情节(示例数据,不是来自原始任务):

【问题讨论】:

  • 请查看更正的问题,谢谢

标签: r plot heatmap


【解决方案1】:

更新

不完全确定您将如何使用 heatmap() 函数,但这种 ggplot 方法可能适合您:

library(ggplot2)
library(dplyr)

# Convert your data into frequency matrix, then data.frame
df<-data.frame(table(data))

# Set columns ready for ggplot
df$Freq<-as.factor(df$Freq)
df$charCount<-as.character(df$charCount) %>% as.numeric()
df$wordCount<-as.character(df$wordCount) %>% as.numeric()

# plot using ggplot
ggplot(df,aes(x=charCount,y=wordCount)) +
    geom_tile(aes(fill=Freq)) +
    geom_text(aes(label=Freq))

如果您想自定义颜色等,可以向 ggplot 行添加其他参数。

【讨论】:

  • 谢谢!用颜色渐变显示对频率也很棒。因此,例如,如果对 (1000, 99) 在数据集中出现 10 次,则对应的点为深红色,而出现 3 次的对 (300, 13) 变为浅蓝色点。任何想法如何做到这一点?
  • 请看我的问题更新。是否可以调整 ggplot x 和 y 最大值以适应小数字?
  • 我认为更新后的答案是您可能正在寻找的,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2016-09-10
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 1970-01-01
  • 2020-10-13
  • 2019-02-13
相关资源
最近更新 更多