如何在ggplot2中做关联图?
How to do an association plot in ggplot2?
我有一个 table 有两个分类值,我想可视化它们的关联;它们在同一行中一起出现的次数。
例如,我们以这个数据框为例:
d <-data.frame(cbind(sample(1:5,100,replace=T), sample(1:10,100,replace=T)))
如何生成这样的热图:
其中方块的颜色表示在给定组合中找到 X1 和 X2 的次数。
最好知道如何用点图来绘制它,其中点的大小表示 X1 和 X2 之间组合出现的次数。
如果你能指导我如何在 ggplot2 或 R 中的任何其他方式上执行此操作,那将非常有帮助。
谢谢!
我会这样做:
library(ggplot2)
library(dplyr)
set.seed(123)
d <-data.frame(x = sample(1:5,100,replace=T), y = sample(1:10,100,replace=T))
d_sum <- d %>%
group_by(x, y) %>%
summarise(count = n())
对于热图:
ggplot(d_sum, aes(x, y)) +
geom_tile(aes(fill = count))
对于点图:
ggplot(d_sum, aes(x, y)) +
geom_point(aes(size = count))
library(ggplot2)
library(dplyr)
library(scales)
set.seed(123)
d <-data.frame(x = sample(1:20,1000,replace=T), y = sample(1:20,1000,replace=T))
d %>% count(x, y) %>% ggplot(aes(x, y, fill = n)) +
geom_tile() +
scale_x_continuous(breaks=1:20)+
scale_y_continuous(breaks=1:20)+
scale_fill_gradient2(low='white', mid='steelblue', high='red') +
guides(fill=guide_legend("Count")) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) + theme_bw()
我有一个 table 有两个分类值,我想可视化它们的关联;它们在同一行中一起出现的次数。
例如,我们以这个数据框为例:
d <-data.frame(cbind(sample(1:5,100,replace=T), sample(1:10,100,replace=T)))
如何生成这样的热图:
其中方块的颜色表示在给定组合中找到 X1 和 X2 的次数。
最好知道如何用点图来绘制它,其中点的大小表示 X1 和 X2 之间组合出现的次数。
如果你能指导我如何在 ggplot2 或 R 中的任何其他方式上执行此操作,那将非常有帮助。
谢谢!
我会这样做:
library(ggplot2)
library(dplyr)
set.seed(123)
d <-data.frame(x = sample(1:5,100,replace=T), y = sample(1:10,100,replace=T))
d_sum <- d %>%
group_by(x, y) %>%
summarise(count = n())
对于热图:
ggplot(d_sum, aes(x, y)) +
geom_tile(aes(fill = count))
对于点图:
ggplot(d_sum, aes(x, y)) +
geom_point(aes(size = count))
library(ggplot2)
library(dplyr)
library(scales)
set.seed(123)
d <-data.frame(x = sample(1:20,1000,replace=T), y = sample(1:20,1000,replace=T))
d %>% count(x, y) %>% ggplot(aes(x, y, fill = n)) +
geom_tile() +
scale_x_continuous(breaks=1:20)+
scale_y_continuous(breaks=1:20)+
scale_fill_gradient2(low='white', mid='steelblue', high='red') +
guides(fill=guide_legend("Count")) +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) + theme_bw()