r - 绘制邻接矩阵时定位不当 - R ggplot

标签 r ggplot2 plot

我想像棋盘一样绘制图形的邻接矩阵(黑色代表 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))

我得到这个输出:

enter image description here

为什么?

最佳答案

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

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()

plot

解释:

  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))

plot

关于r - 绘制邻接矩阵时定位不当 - R ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52924536/

相关文章:

r - 使用 ggplot2 修改点子集的形状

r - ggplot2 采购错误 : X11 library is missing

r - 在ggplot中存在非线性回归问题

user-interface - 如何在 Octave 中编写 slider 以获得交互式绘图?

r - 向轴标签添加逗号分隔符

r - 标记 geom_points,但不是全部

r - R中的set.seed的参数

r - 在R中使用过滤功能但收到错误消息

r - 仅绘制特定轴文本标签

python - 从绘图屏幕上单击的两点画线,然后删除艺术家