我正在使用该plotly包,我正在尝试向图表添加水平线.有没有办法用剧情来做?
它可以使用ggplot2和完成ggplotly如下所示的功能:
library(plotly)
p <- ggplot() +
geom_hline(yintercept = 4) +
xlim(c(0,10)) +
ylim(c(0,10))
ggplotly(p)
Run Code Online (Sandbox Code Playgroud)
但我无法将其添加到现有的阴谋图中.
此外,我的图表的轴不固定,因此很难(但不是不可能)只为水平线计算出x和y坐标系,但我宁愿自动添加一个.
我已经查看了y0和dy参数,但我似乎无法获得那些工作的代码.我不太确定他们到底做了什么,但我认为他们可能正在寻找什么?我找不到他们用法的好例子.
Car*_*son 32
有很多方法可以做到这一点(使用数据或'纸'坐标).假设数据坐标,最简单的当前方式是add_segments():
plot_ly() %>%
add_segments(x = 4, xend = 4, y = 0, yend = 10) %>%
add_segments(x = 3, xend = 5, y = 5, yend = 5)
Run Code Online (Sandbox Code Playgroud)
注意我们如何在数据坐标中硬编码这些线的范围; 因此,当缩放和平移绘图时,该行将被"剪切"到这些值.如果您不希望剪切这些线条,请使用将xref/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)))
Run Code Online (Sandbox Code Playgroud)
use*_*362 11
或者,您可以在布局()下添加形状(即线条).以下示例添加一条垂直线:
p <- plot_ly(data, x = ~x.data, y = ~y.data, text = ~text.data, type = 'scatter',
mode = 'markers', marker = list(size = ~size.data, opacity= 0.5)) %>%
layout(shapes=list(type='line', x0= 0.2, x1= 0.2, y0=min(allyvalues), y1=max(allyvalues), line=list(dash='dot', width=1)),
title = 'This is the Title',
xaxis = list(title = "X-Axis", showgrid = TRUE),
yaxis = list(title = "Y-Axis", showgrid = TRUE))
p
Run Code Online (Sandbox Code Playgroud)