利用ggplot2画发文章级别的TSNE图

我们一般用R语言画出来的TSNE图是这样的,但是如果要发文章的话,一般是需要再美化一下的,这是一般的图:

image.png

好了,话不多话,今天来教大家如何进行修改。直接上代码:
1.安装程序包,读取数据

package.list=c("ggplot2","pals","dplyr")
for (package in package.list) {
  if (!require(package,character.only=T, quietly=T)) {
    install.packages(package)
    library(package, character.only=T)
  }
}
data<-read.csv("data.csv")

2.自定义主题,颜色,可以用pals::glasbey()里颜色,也可以自己指定颜色

define_theme <- theme(
  panel.background = element_blank(),
  panel.border = element_blank(),
  panel.grid = element_blank(), 
  axis.title = element_text(color='black', size=18),
  axis.ticks.length = unit(0.4, "lines"),
  axis.ticks = element_blank(),
  axis.line = element_blank(),
  axis.text = element_blank(),
  legend.title = element_blank(),
  legend.text = element_text(size=18),
  legend.key = element_blank(),
  legend.key.size = unit(1, 'cm')
) 
define_color1 <- pals::glasbey()[1:26]
define_color2 <- c("#DC050C","#FB8072","#1965B0","#7BAFDE","#882E72",
                   "#B17BA6","#FF7F00","#FDB462","#E7298A","#E78AC3",
                   "#33A02C","#B2DF8A","#55A1B1","#8DD3C7","#A6761D",
                   "#E6AB02","#7570B3","#BEAED4","#666666","#999999",
                   "#aa8282","#d4b7b7","#8600bf","#ba5ce3","#808000",
                   "#aeae5c","#1e90ff","#00bfff","#56ff0d","#ffff00")[1:26]

3.设置标签坐标位置

df_label <- summarise(group_by(data, cluster), 
                      x_pos = mean(TSNE_1), 
                      y_pos = mean(TSNE_2))

4.ggplot2开始画图

p <- ggplot(data, aes(x = TSNE_1, y = TSNE_2)) +
  geom_point(aes(color = cluster), alpha = .7) +
  scale_color_manual(values = define_color2) +
  geom_label(aes(x_pos, y_pos, label = cluster), 
             data = df_label, 
             label.r = unit(0.2, 'lines'),
             alpha = .5, 
             size = 5) +
  theme_bw() +
  define_theme +
  guides(colour = guide_legend(override.aes = list(size = 5))) +
  geom_segment(aes(x = min(TSNE_1) - 10, 
                   y = min(TSNE_2) - 10,
                   xend = min(TSNE_1) + 90, 
                   yend = min(TSNE_2) - 10),
               colour = "black", 
               size = 1,
               arrow = arrow(length = unit(0.3,"cm"))) + 
  geom_segment(aes(x = min(TSNE_1) - 10,
                   y = min(TSNE_2) - 10,
                   xend = min(TSNE_1) - 10, 
                   yend = min(TSNE_2) + 90),
               colour = "black", 
               size = 1,
               arrow = arrow(length = unit(0.3,"cm")))
ggsave(plot = p, filename = 'tsne.png', dpi = 300, width = 10, height = 8)

最终修改好的图片效果如下:

image.png

**代码中用到的案例数据,可以到我的博客中下载,http://81.69.237.191

你可能感兴趣的:(利用ggplot2画发文章级别的TSNE图)