[英]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 坐標系,但我寧願自動添加一個。
我已經研究了 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)))
或者,您可以在 layout() 下添加一個形狀(即線條)。 以下示例添加了一條垂直線:
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
基於上面卡森的好答案,這里有一個更接近 ggplot 的geom_vline()
的便利函數
# Add vertical line(s) at position x to plotly plot p
# Additional arguments: color, width (px), dash ('solid','dot', 'dash', etc)
# See https://plotly.com/r/reference/#layout-shapes-items-shape-line
add_vline = function(p, x, ...) {
l_shape = list(
type = "line",
y0 = 0, y1 = 1, yref = "paper", # i.e. y as a proportion of visible region
x0 = x, x1 = x,
line = list(...)
)
p %>% layout(shapes=list(l_shape))
}
為了使函數可加,可以對函數進行以下修改
add_vline = function(p, x, ...) {
if(!is.null(p$x$layoutAttrs)){
index <- unname(which(sapply(p$x$layoutAttrs, function(x)
!is.null(x$shapes))))
} else {
index <- integer()
}
l_shape = list(
type = "line",
y0 = 0, y1 = 1, yref = "paper", # i.e. y as a proportion of visible region
x0 = x, x1 = x,
line = list(
...
),
layer = "below"
)
if(length(index) > 0){
shapes <- p$x$layoutAttrs[[index]]$shapes
shapes[[length(shapes) + 1]] <- l_shape
p$x$layoutAttrs[[index]]$shapes <- shapes
} else {
p <- plotly::layout(
p = p,
shapes = list(l_shape)
)
}
p
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.