在Rshiny

时间:2016-05-16 19:02:46

标签: r ggplot2 shiny plotly geom-text

我正在使用Rshiny绘图来创建带有文本标签的散点图。以下是一个可重复的例子:

library(ggplot2)
library(plotly)
dat <- data.frame(LongExpressionValue = rnorm(1:100), 
                  LongMethylationValue = rnorm(1:100), 
                  LongCopyNumberValue = rnorm(1:100))

rownames(dat) <- paste0('n',seq(1:100))

# ggplot
p <- ggplot(data = dat, aes(x = LongExpressionValue, y = LongMethylationValue)) + 
  geom_point(size = 2) + geom_smooth(method = lm) +
  geom_text(aes(label = rownames(dat)), vjust=-1.5, size = 3)

# ggplotly
ggplotly(p)

这会产生如下情节:

enter image description here

如何调整我的geom_text选项,使标签显示在上方而不与点重叠?我确实希望保留我的ggplot代码,以便跨应用程序使用它。

谢谢!

3 个答案:

答案 0 :(得分:2)

试试这个:

plot_ly(data = dat, 
        x = LongExpressionValue, 
        y = LongMethylationValue, 
        text = rownames(dat), 
        marker = list(size = 10), 
        mode = "markers+text",
        textposition = 'top center')

当您可以直接访问源代码时,不值得在ggplot2上努力工作。这是非常宝贵的:https://plot.ly/r/reference/

plot_lylayout中的所有内容都是列表,因此您可以轻松设置参数(请注意marker = list(size = 10)

编辑:稍微复杂一点,显示hoverinfo +文字的强大功能:

plot_ly(data = dat, 
        x = LongExpressionValue, 
        y = LongMethylationValue, 
        text = paste0(rownames(dat), 
                      '<br>A:', 1:nrow(dat), #Examples of additional text
                      '<br>B:', sample(nrow(dat))), #Examples of additional text
        hoverinfo = 'text+x+y',
        marker = list(size = 10), 
        mode = "markers+text",
        hoverinfo = 'text',
        textposition = 'top right')

答案 1 :(得分:1)

如果您想坚持使用ggplot2并保持平滑的线条,您可以稍微增加点的大小,并在每个点内添加标签:

p <- ggplot(data = dat, aes(x = LongExpressionValue, y = LongMethylationValue)) + 
  geom_point(size = 7) + geom_smooth(method = lm) +
  geom_text(aes(label = rownames(dat)), size = 2, color="white")

# ggplotly
ggplotly(p)

enter image description here

答案 2 :(得分:1)

如果您想留在 ggplot2 ,则必须在textposition列表中添加plotly_build元素。即使设置了textpositionplotly_build选项,原始hjust中也会遗漏vjust

这样可行:

#devtools::install_github("ropensci/plotly") # if not already done
library(ggplot2)
library(plotly) 
dat <- data.frame(LongExpressionValue = rnorm(1:100),
              LongMethylationValue = rnorm(1:100),
              LongCopyNumberValue = rnorm(1:100))

rownames(dat) <- paste0('n',seq(1:100))  

gg <- ggplot(data = dat, aes(x = LongExpressionValue, y =LongMethylationValue)) + 
geom_point(size = 1) +
geom_smooth(method = lm) +
geom_text(aes(label = rownames(dat)), size = 3)

p <- plotly_build(gg)

length<-length(p$x$data)
invisible(lapply(1:length, function(x) p$x$data[[x]]<<-c(p$x$data[[x]], textposition ='top center')))

p