在R中的绘图折线图中的线的中间部分添加注释

时间:2020-10-23 09:18:26

标签: r plotly r-plotly

我正尝试在r-plot折线图中将文本注释添加到每条线的中心部分,如下面的图1 所示。但是,文本注释显示在该行的任一端,如图2 所示。有人可以帮忙解决此问题吗?

enter image description here

library(plotly)
library(RColorBrewer)

df <- read.csv("https://cdn.rawgit.com/plotly/datasets/master/GanttChart-updated.csv", stringsAsFactors = F)
df$Start <- as.Date(df$Start, format = "%m/%d/%Y")
client = "Sample Client"
cols <- brewer.pal(length(unique(df$Resource)), name = "Set3")
df$color <- factor(df$Resource, labels = cols)

p <- plot_ly()

for(i in 1:(nrow(df) - 1)){
    p <- add_trace(p,
             x = c(df$Start[i], df$Start[i] + df$Duration[i]),
             y = c(i, i), 
             mode = "lines",
             line = list(color = df$color[i], width = 30),
             showlegend = F,
             hoverinfo = "text",                
             text = paste("Task: ", df$Task[i], "<br>",
                          "Duration: ", df$Duration[i], "days<br>",
                          "Resource: ", df$Resource[i]),
             evaluate = T  
   )
 p <- add_annotations(p,
                      x = c(df$Start[i], df$Start[i] + df$Duration[i]),  
                      y = c(i, i),  
                      xref = "x",
                      yref = "y",
                      mode = "text",
                      text = df$Task[i],
                      textposition = 'middle',
                      textfont = list(color = '#000000', size = 16)
   )
 }

p

0 个答案:

没有答案