R 热图新手:绘图对计数

R heatmap newbie: plot pair counts

我需要创建一个热图来显示不同的 (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))

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

已更新

不确定如何使用 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 行添加其他参数。