如何通过标记在标记中绘制水平线?

时间:2017-07-11 13:26:52

标签: r plot plotly

这是我编写的一些示例代码来说明我的问题。现在,情节仅生成点数。我想要做的是穿过每个点的水平线,每边长度为1。 (即(2,1)点我希望该行从(1,1)运行到(3,1))我如何在plotly中执行此操作?我看了here,但是当y轴不是数字时,我似乎无法弄清楚如何使它工作。

library(plotly)

p <- plot_ly(data = mtcars, x = ~mtcars$mpg, y = rownames(mtcars), type = 'scatter', mode = 'markers')
p

编辑 Here是接受答案中提供的代码的输出(显示所有车名除外)。我想知道是否有办法在每个y轴标签之间绘制一条水平线,例如,在&#34; Volvo 142E&#34;之间。和&#34;玛莎拉蒂宝来&#34;,一条线将它们分开,然后按照情节的长度进行。现在,情节的每条水平线都有一个点。我想将这些行与另一行分开。

1 个答案:

答案 0 :(得分:1)

为了实现这一点,我们不得不使用行索引重新绘制原始散点图,以防止重新排序汽车。然后我添加回轴标签。

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

根据OP的请求进行更新。

以图形方式使用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"))