如何在热图上更改颜色等

时间:2020-06-25 13:15:36

标签: r ggplot2

很抱歉,是新手问题。我试图制作一个热图图。这是我得到的:

enter image description here

看起来很丑。我想知道是否可以为图形选择颜色。如果是这样,怎么办?我想使用黄色红色而不是蓝色,而红色具有最多的obs。还有什么方法可以使这张图看起来更好,更专业?任何示例代码都将对我学习这种类型图有很大帮助。另外,我的变量不是连续的。我应该如何解决它不会设置为1.5、2.5的问题?

这是我编写的示例数据和代码:

ID<- c("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18")
Group<-c("A","B","C","D","D","D","A","B","D","C","B","D","A","A","C","B","B","B")
Color<-c("Green","Blue","Red","Red","Black","Yellow","Green","Green","Yellow","Purple","Red","Yellow","Yellow","Yellow","Green","Red","Red","Green")
Realy_Love<-c("Y","N","Y","Y","N","N","Y","Y","Y","N","N","Y","N","Y","N","Y","N","Y")
Sample.data <- data.frame(ID, Group, Color, Realy_Love)
        
Sample.data %>%
  count(Group, Color, sort = TRUE) %>% ggplot(aes(x = Group, y = Color, fill=n)) + geom_raster() +
geom_text(aes(label = paste0("N=",round(n, 1)), color = n < 100),show.legend = F)+
  guides(fill = guide_legend())

非常感谢。

1 个答案:

答案 0 :(得分:2)

我将做几件事来改善此处的外观。首先,使用scale_fill_manual设置图块的颜色。其次,使用coord_equal使图块方形。第三,使文本为黑色而不是红色。第四,将主题元素设置为theme_minimal设置。

这当然可能并不符合所有人的口味,但对我而言肯定更好。我认为您可能希望尝试使用不太鲜艳的颜色以获得更专业的外观。

Sample.data %>%
  count(Group, Color, sort = TRUE) %>% 
  ggplot(aes(x = Group, y = Color, fill = factor(n, levels = 3:1))) + 
  geom_raster() +
geom_text(aes(label = paste0("N=",round(n, 1))), 
          color = "black", show.legend = FALSE) +
  guides(fill = guide_legend("n")) + 
  theme_minimal() +
  scale_fill_manual(values = c("yellow", "orange", "red")) +
  coord_equal()

enter image description here