绘制邻接矩阵时的不正确定位 - R ggplot

and*_*and 2 plot r ggplot2

我想绘制一个像棋盘的图形的邻接矩阵(黑色表示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
Run Code Online (Sandbox Code Playgroud)

使用以下代码:

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))
Run Code Online (Sandbox Code Playgroud)

我得到这个输出:

在此输入图像描述

为什么?

Z.L*_*Lin 5

以下代码应返回您要查找的内容:

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()
Run Code Online (Sandbox Code Playgroud)

情节

说明:

  1. 使用命名向量通常更安全scale_XX_manual,以确保映射正确的值;
  2. 默认情况下,绘图的原点位于左下角,而不是左上角.如果您希望它从顶部开始,请反转您的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))
Run Code Online (Sandbox Code Playgroud)

情节