我正在按照一个示例here在R中创建项目符号图表,我坚持的最后一部分是尝试向每个数据元素添加数据标签。
我认为使用text =''会很简单,但是标签不会显示,并且代码可以正常运行。
我想在内部和外部条形图的内侧加上标签。
我认为它可能有一些做使用附加&detatch但我不能完全确定。非常感谢您的协助。
更新:添加样本数据以供参考:
library(plotly)
library(dplyr)
library(readxl)
# Read data
zz <- "name distance office
name1 3200 3900
name2 3000 6900
name3 1700 5900
name4 1500 3500
name5 1200 2700
name6 1000 3700
name7 1000 1600
name8 1000 4100
name9 1000 6800
name10 800 2000
name11 700 2800
name12 700 6900
name13 700 2100
name14 500 5400
name15 400 1300
name16 400 0"
df<- read.table(text=zz, header = TRUE)
attach(df)
df<-df[order(-Distance),]
detach(df)
# df <- as.data.frame(df, stringsAsFactors = F)
p <- list()
# Set line widths
innerwidth <- 10
outerwidth <- 25
for(i in 1:nrow(df)){
attach(df[i,])
p[[i]] <-
plot_ly() %>%
add_segments(x = 0,
xend = as.numeric(Office),
y = Name,
yend = Name,
name = "Office",
mode = 'text',
text = rownames(Office),
hoverinfo = "x",
line = list(color = "#eeeeee", width = outerwidth)) %>%
add_segments(x = 0,
xend = as.numeric(Distance),
y = Name,
yend = Name,
name = "Distance",
mode = 'markers+text',
text = ~Distance,
textposition = 'auto',
hoverinfo = "x",
line = list(color = "#b0c4de", width = innerwidth)) %>%
layout(showlegend = F,
xaxis = list(Name = "", showgrid = F,
range = c(0, 7000),
showticklabels = FALSE,
showline = FALSE,
ticklen = 0,
tickfont = list(family = "Arial", size = 10),
tickcolor = "#cccccc"))
detach(df[i,])
}
pp <- subplot(p[[1]], p[[2]], p[[3]], p[[4]],
p[[5]], p[[6]], p[[7]], p[[8]],
p[[9]], p[[10]],p[[11]],p[[12]],
p[[13]], p[[14]], p[[15]],
p[[16]],
nrows = 17,
margin = c(0, 0, 0,0))
pp