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