How to plot horizontal lines through markers in plotly?

瘦欲@ 提交于 2019-12-11 06:27:59

问题


Here is some example code I wrote to illustrate my problem. Right now, the plot generates only the points. What I want to do is have horizontal lines that go through each point, spanning a length of 1 to each side. (i.e. for a point at (2,1) I want the line to run from (1,1) to (3,1)) How can I do this in plotly? I've looked here but can't seem to figure out how to get this to work when the y-axis is not numerical.

library(plotly)

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

EDIT is the output from the code provided in the accepted answer (except showing all car names). I was wondering if there is a way to draw a horizontal line between each y-axis label, so that for example, between "Volvo 142E" and "Maserati Bora", a line separates them, and goes for the length of the plot. Right now, each horizontal line of the plot has a point on it. I want to separate each of those lines with another line.


回答1:


To get this to work we had to replot the original scatter plot with an using the row index to prevent plotly from reordering cars. Then I added back to the axis labels.

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

Update based on OP's request.

To underline text in plotly use HTML tags. But <u> </u> does not work so we have to use <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"))


来源:https://stackoverflow.com/questions/45035921/how-to-plot-horizontal-lines-through-markers-in-plotly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!