[英]How to plot horizontal lines through markers in plotly?
这是我编写的一些示例代码来说明我的问题。 现在,该图仅生成点。 我想要做的是穿过每个点的水平线,每边的长度为 1。 (即对于(2,1)
处的一个点,我希望该线从(1,1)
运行到(3,1)
)我怎样才能在plotly
做到这plotly
? 我看过here但似乎无法弄清楚当y轴不是数字时如何让它工作。
library(plotly)
p <- plot_ly(data = mtcars, x = ~mtcars$mpg, y = rownames(mtcars), type = 'scatter', mode = 'markers')
p
编辑 是接受的答案中提供的代码的输出(显示所有汽车名称除外)。 我想知道是否有一种方法可以在每个 y 轴标签之间绘制一条水平线,例如,在“沃尔沃 142E”和“玛莎拉蒂 Bora”之间,一条线将它们分开,并代表情节的长度。 现在,绘图的每条水平线上都有一个点。 我想将每一行与另一行分开。
为了让它起作用,我们必须使用行索引重新绘制原始散点图,以防止 plotly 重新排序汽车。 然后我添加回轴标签。
library(plotly)
##I added the text argument(hover over text) so that I could make sure
##that the yaxis labels matched the points. feel free to delete.
p <- plot_ly(x = mtcars$mpg, y = seq_along(rownames(mtcars)), text=rownames(mtcars),
type = 'scatter', mode = 'markers')
##This sets some attributes for the yaxis. Note: in your origianl plot every other
##car name was shown on the y-axis so that is what I recreated but you could remove
##the "seq(1,32, by=2)" to show all car names.
ax <- list(
title = "",
ticktext = rownames(mtcars)[seq(1,32, by=2)],
tickvals = seq(1,32, by=2)
)
##This is taken from the plotly help page. y0 and y1 now are set to equal the row
##number and x0 and x1 are +/-1 from the car's mpg
line <- list(
type = "line",
line = list(color = "pink"),
xref = "x",
yref = "y"
)
lines <- list()
for (i in seq_along(rownames(mtcars))) {
line[["x0"]] <- mtcars$mpg[i] - 1
line[["x1"]] <- mtcars$mpg[i] + 1
line[c("y0", "y1")] <- i
lines <- c(lines, list(line))
}
p <- layout(p, title = 'Highlighting with Lines', shapes = lines, yaxis=ax)
p
要在 plotly 中为文本加下划线,请使用 HTML 标签。 但是<u> </u>
不起作用所以我们必须使用<span> </span>
...
ax2 <- list(
title = "", ticktext = paste0('<span style="text-decoration: underline;">',
rownames(mtcars)[1:32 %% 2 ==0],"</span>"),
tickvals = seq(1,32, by=2), style=list(textDecoration="underline"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.