我想像棋盘一样绘制图形的邻接矩阵(黑色代表 1,白色代表 0,反之亦然)
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 0 0
[2,] 1 0 0 0 0
[3,] 1 0 0 0 0
[4,] 1 0 0 0 0
[5,] 1 0 0 0 0
使用以下代码:
require(igraph)
require(ggplot2)
require(reshape2)
g <- make_star(5)
gAdjMatrix <- as.matrix(as_adj(g))
print(gAdjMatrix)
logMatrix <- (gAdjMatrix == 1)
logMatrix
mm <- logMatrix
mm %>%
melt() %>%
ggplot(aes(Var2, Var1)) +
geom_tile(aes(fill = value,
color = value)) +
coord_equal() +
scale_fill_manual(values = c("black", "white")) +
scale_color_manual(values = c("white", "black")) +
theme_bw() +
theme(axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
panel.grid = element_blank()) +
guides(fill = FALSE, color = FALSE) +
scale_x_discrete(expand = c(0,0)) +
scale_y_discrete(expand = c(0,0))
我得到这个输出:
为什么?
最佳答案
以下代码应返回您要查找的内容:
mm %>%
melt() %>%
ggplot(aes(Var2, Var1)) +
geom_tile(aes(fill = value,
color = value)) +
coord_equal() +
scale_fill_manual(values = c("TRUE" = "black", "FALSE" = "white")) +
scale_color_manual(values = c("TRUE" = "white", "FALSE" = "black")) +
theme_bw() +
theme(axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
panel.grid = element_blank()) +
guides(fill = FALSE, color = FALSE) +
scale_y_reverse()
解释:
- 在
scale_XX_manual
中使用命名向量通常更安全,以确保映射正确的值; - 默认情况下,绘图的原点位于左下角,而不是左上角。如果您希望它从顶部开始,请反转您的 y 轴。
旁注:您可以在将来尽量减少此类问题,方法是在完成对情节的更重要方面的调整之前,省略与外观相关的代码。如果您在图中留下轴和图例标签,上述问题可能更容易发现:
mm %>%
melt() %>%
ggplot(aes(Var2, Var1)) +
geom_tile(aes(fill = value,
color = value)) +
coord_equal() +
scale_fill_manual(values = c("black", "white")) +
scale_color_manual(values = c("white", "black")) +
theme_bw() #+
# theme(axis.title = element_blank(),
# axis.text = element_blank(),
# axis.ticks = element_blank(),
# panel.grid = element_blank()) +
# guides(fill = FALSE, color = FALSE) +
# scale_x_discrete(expand = c(0,0)) +
# scale_y_discrete(expand = c(0,0))
关于r - 绘制邻接矩阵时定位不当 - R ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52924536/