ggplot2_bubble

 

昨天心血来潮想试试用 ggplot2 画类似 D3.js 的那种气泡图,心动不如行动,说干就干!

首先呢,我们先把包加载一下下,再把theme调整一下下。
没用的妖艳贱货全都走开。

library(ggplot2)
library(gridExtra)
theme_set(
  theme_bw() +
    theme(
      axis.line = element_blank(),
      axis.title = element_blank(),
      axis.text = element_blank(),
      axis.ticks = element_blank(),
      panel.grid = element_blank(),
      panel.border = element_blank()
    )
)

然后导入一哈数据。

非常遗憾的是, ggplot2 并没有自带的 circle 函数,因此我利用 stat_ellipse 作为替代方案。
为了让画出来的圆尽量平滑一下,将 point 的数量设置的相对多一些。

circle_df <- function(center_x, center_y, r){
  angles = seq(0, 360, 360 / 50000)

  cir_df = data.frame(
    point_x = center_x + r * sin(angles),
    point_y = center_y + r * cos(angles)
  )
  
  return(cir_df)
  
}

接下来就是重构的气泡图了,进行一些角度的运算就可以啦。

bubble_plot <- function(plot_data, alpha = 1){
  cir_num = nrow(plot_data)
  angles = (seq(0, 1, by = 1/cir_num)[-1]) * 2 + sample(seq(0,1, 1000), 1)
  init_r = max(plot_data[,3]) * cir_num / 2
  x_axis = (init_r + plot_data[,3])  * cospi(angles) * 0.9
  y_axis = (init_r + plot_data[,3]) * sinpi(angles) * 0.9
  random_index  = sample(1:cir_num, cir_num, replace = F)
  new_plot_df <- data.frame(
    x = x_axis,
    y = y_axis,
    text = unlist(plot_data[random_index,2]),
    s = plot_data[random_index,3]
  )
  init_cir = ggplot(data = circle_df(center_x = 0,center_y = 0, r= init_r), aes(point_x, point_y)) +
    stat_ellipse(geom = "polygon", fill = "white", level = 0.95) +
    geom_text(
      data = data.frame(x = 0, y = 0, text = plot_data[1,1]),
      aes(x,y,label = text),
      size = 6
    ) +
    coord_equal() +
    scale_size(200)
  for(i in 1:cir_num){
    cir_df = circle_df(center_x = new_plot_df[i,1],center_y = new_plot_df[i,2], r= new_plot_df[i,4])
    init_cir = init_cir + 
      stat_ellipse(
        data  = cir_df, 
        aes(point_x, point_y),
        geom = "polygon", 
        fill = plot_data[i,4],
        alpha = alpha,
        level = 0.95
        ) +
      geom_text(
        data = new_plot_df[i,],
        aes(x,y, label = text),
        size = 3
      )
  }
  return(init_cir)
}

最后我们来看一下最终得到的结果:

lncRNA_plot_df <- data.frame(
  x = lncRNA_df[,1],
  y = lncRNA_df[,2],
  s = lncRNA_df[,3],
  fill = rainbow(nrow(lncRNA_df), start = .1, end = .9)
)
bubble_plot(lncRNA_plot_df, alpha = 0.4)


等画完了突然发现,为什么我不直接用 cytoscape 画呢?
我这个人的唯一优点就是: 想不通就不想了。

posted @ 2018-10-12 14:34  PeRl`  阅读(145)  评论(0编辑  收藏  举报