绘图中的水平/垂直线 [英] Horizontal/Vertical Line in plotly
问题描述
我正在使用plotly
程序包,并试图向图形添加水平线.有什么方法可以使用plotly吗?
可以使用ggplot2
和ggplotly
函数来完成此操作,如下所示:
library(plotly)
p <- ggplot() +
geom_hline(yintercept = 4) +
xlim(c(0,10)) +
ylim(c(0,10))
ggplotly(p)
但是我不能将其添加到现有的绘图区中.
此外,我的图表的轴不是固定的,因此很难(但并非不可能)仅计算一条水平线的x和y坐标系,但我宁愿只自动添加一个. /p>
我已经研究了y0和dy参数,但是我似乎也无法获得使它们起作用的代码.我不太确定他们到底要做什么,但是我认为他们也许正是我想要的?我找不到它们用法的好例子.
有两种主要方法(使用数据或纸"坐标).假设数据坐标,最简单的当前方法是通过add_segments()
:
plot_ly() %>%
add_segments(x = 4, xend = 4, y = 0, yend = 10) %>%
add_segments(x = 3, xend = 5, y = 5, yend = 5)
注意我们如何在数据坐标中对这些行的范围进行硬编码;因此,缩放和平移绘图时,该线将被剪切"为这些值.如果您不希望这些线条被剪切,请使用线条形状与外部参照/yref设置为纸张(这会将图形区域设置为0-1比例,而不是x/y数据比例):
vline <- function(x = 0, color = "red") {
list(
type = "line",
y0 = 0,
y1 = 1,
yref = "paper",
x0 = x,
x1 = x,
line = list(color = color)
)
}
hline <- function(y = 0, color = "blue") {
list(
type = "line",
x0 = 0,
x1 = 1,
xref = "paper",
y0 = y,
y1 = y,
line = list(color = color)
)
}
plot_ly() %>%
layout(shapes = list(vline(4), hline(5)))
I'm using the plotly
package and I'm trying to add a horizontal line to a graph. Is there any way of doing it using plotly?
It can be done using ggplot2
and the ggplotly
function as shown below:
library(plotly)
p <- ggplot() +
geom_hline(yintercept = 4) +
xlim(c(0,10)) +
ylim(c(0,10))
ggplotly(p)
But I can't add this to an existing plotly plot.
Also, the axis of my charts are not fixed, so it would be difficult (but not impossible) to just work out an x and y coordinate system for a horizontal line, but I'd rather just add one automatically.
I've looked into the y0 and dy arguments, but I can't seem to get the code for those to work, either. I'm not quite sure what they do exactly, but I think they're maybe what I'm looking for? I can't find good examples of their usage.
There are two main ways to do this (using either data or 'paper' coordinates). Assuming data coordinates, the easiest current way is via add_segments()
:
plot_ly() %>%
add_segments(x = 4, xend = 4, y = 0, yend = 10) %>%
add_segments(x = 3, xend = 5, y = 5, yend = 5)
Notice how we've hard coded the extent of these lines in data coordinates; so when zooming and panning the plot, the line will be "clipped" at those values. If you don't want these lines to be clipped, use a line shape with xref/yref set to paper (this puts the graph region on a 0-1 scale, rather than on the x/y data scale):
vline <- function(x = 0, color = "red") {
list(
type = "line",
y0 = 0,
y1 = 1,
yref = "paper",
x0 = x,
x1 = x,
line = list(color = color)
)
}
hline <- function(y = 0, color = "blue") {
list(
type = "line",
x0 = 0,
x1 = 1,
xref = "paper",
y0 = y,
y1 = y,
line = list(color = color)
)
}
plot_ly() %>%
layout(shapes = list(vline(4), hline(5)))
这篇关于绘图中的水平/垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!