首页 > 解决方案 > 表格和热图

问题描述

我正在尝试制作热图表。我想要一个类似于下表的表格。

在此处输入图像描述

下面你可以看到数据和代码。

TestData1<-structure(list(Countries = c("AL", "CA", "DE", "ES", "MA", "EL", 
                                        "AL", "CA", "DE", "ES", "MA", "EL", "AL", "CA", "DE", "ES", "MA", 
                                        "EL"), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 
                                                                      2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("Total", 
                                                                                                                          "Female", "Male"), class = "factor"), value = c(-3.06, -4.41, 
                                                                                                                                                                          6.97, -2.74, 5.54, -1.31, -2.47, -3.45, 4.11, -3.06, 4.82, -1.73, 
                                                                                                                                                                          -3.95, -5.76, 8.74, -1.87, 6.37, -0.79)), row.names = c(NA, -18L
                                                                                                                                                                          ), class = "data.frame")


ggplot(TestData1, aes(x = 'Countries', y = factor(variable, levels = rev(levels(factor(variable)))))) + 
  geom_tile(aes(fill = value)) +
  geom_text(aes(label = value), color = "white") + 
  scale_x_discrete(position = "top") +
  scale_fill_gradient(high = "#132B43", low = "#56B1F7") +
  theme(legend.position = "none", 
        panel.grid = element_blank(), 
        panel.background = element_rect(fill = "white"),
        axis.ticks = element_blank()) +
  labs(y = " ")

但不幸的是,最终的结果并不好。那么任何人都可以帮助我如何制作像上表一样的热图吗?

标签: rggplot2heatmap

解决方案


试试看!;)

ggplot(TestData1, aes(x = variable, y = Countries)) + 
  geom_tile(aes(fill = value)) +
  geom_text(aes(label = value), color = "white") + 
  scale_x_discrete(position = "top")  +
  scale_y_discrete(limits = rev) +
  scale_fill_gradient(high = "#132B43", low = "#56B1F7") +
  theme(legend.position = "none", 
        panel.grid = element_blank(), 
        panel.background = element_rect(fill = "white"),
        axis.ticks = element_blank()) +
  labs(y = " ", x = " ")

推荐阅读