简体   繁体   中英

How to plot horizontal lines through markers in plotly?

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. (ie 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.

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM