[英]Modify aesthetic mapping in ggplot2 to obtain correct plotly legend
我有一個ggplot2
圖表,我想用plotly
渲染。 x
和y
變量是從字符變量中獲得的,如下例所示:
library(ggplot2)
library(plotly)
dset <- data.frame(x = runif(10), y = runif(10))
head(dset)
#> x y
#> 1 0.45902147 0.9842178
#> 2 0.04331170 0.8337590
#> 3 0.02202882 0.8607866
#> 4 0.27971306 0.4250171
#> 5 0.35531015 0.7182533
#> 6 0.61235609 0.9905286
# vars for x and y aesthetics
varx <- "x"
vary <- "y"
# ggplot2 chart
p <-
ggplot(dset, aes(get(varx), get(vary))) + xlab(varx) + ylab(vary) + geom_point()
# convert to plotly
ggplotly(p)
plotly
輸出在工具提示中顯示get(varx)
,我希望它顯示x
。 我相信文字是從美學映射繼承的。
print(p[[4]])
#> Aesthetic mapping:
#> * `x` -> `get(varx)`
#> * `y` -> `get(vary)`
由reprex 包(v0.3.0) 於 2020 年 1 月 20 日創建
有沒有辦法在將圖表轉換為plotly
之前更改美學映射? 如果沒有,在plotly
修改工具提示的最簡單方法是什么?
編輯:
只需使用aes_string()
而不是aes()
。 第一個需要明確引用輸入(而不是aes
使用的標准評估)
p <- ggplot(dset, aes_string(varx, vary)) +
xlab(varx) +
ylab(vary) +
geom_point()
ggplotly(p)
原答案:
我設法按照此頁面進行操作: https://plot.ly/r/hover-text-and-formatting/ ,但您必須通過plot_ly()
函數構建繪圖。 這是更多的編碼,但你可以更好地控制情節的外觀。 從那里您可以將變量粘貼到hovertemplate()
和layout()
以獲取工具提示和軸標簽。
dset %>%
plot_ly() %>%
add_trace(
type = 'scatter',
mode = 'markers',
x = ~get(varx),
y = ~get(vary),
hovertemplate = paste(
paste(varx,": %{x:.f}<br>"),
paste(vary,": %{y:.f}<br>")
)
) %>%
layout(xaxis = list(title = paste(varx)),
yaxis = list(title = paste(vary)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.