我在使用相同绘图图形上的多个轨迹在标记上显示文本时遇到了问题。代码如下:
plot_ly(x = ~SWITCHING_SUMS_NET()$week, y = ~SWITCHING_SUMS_NET()$V1,
name = 'Affordability', type = 'scatter', mode = 'lines+markers',
text=~SWITCHING_SUMS_NET()$V1, textposition="top center") %>%
add_trace(y = ~SWITCHING_SUMS_NET()$V2, name = 'Experience Change',
mode = 'lines+markers', text=~SWITCHING_SUMS_NET()$V2) %>%
add_trace(y = ~SWITCHING_SUMS_NET()$V3, name = 'Unavailability',
mode = 'lines+markers', text=~SWITCHING_SUMS_NET()$V3) %>%
add_trace(y = ~SWITCHING_SUMS_NET()$V4, name = 'Attracted buy another brand',
mode = 'lines+markers', text=~SWITCHING_SUMS_NET()$V4) %>%
layout(xaxis = list(title = ''),
yaxis = list (title = 'Count',showticklabels = T),
legend = list(orientation = 'h', xanchor = "center",x = 0.5,y= -0.3))输出图像:

发布于 2020-06-30 09:25:09
无论何时你必须在add_trace中做多个绘图(或其他绘图函数),或者在ggplot中做geom,研究从宽到长重塑你的数据框架的可能性。这样,您就可以创建一个grouping列,并且只执行一个add_trace (下面是ggplot2:Making multi-line plots in R using ggplot2的示例)。
此外,最好使用反应函数将数据读入绘图函数之外的shiny (即plot_data <- SWITCHING_SUMS_NET())中的变量。这样,您可以在以后对数据应用过滤器、整形或其他必要功能,并且只需最少的编辑即可再次生成您的绘图。此外,您的输入数据保持不变。
考虑到上面的提示,这是解决这个问题的最好方法。在这里,我有两个跟踪,一个用于文本,另一个用于标记和行(在plot_ly函数本身内)。另一种方法是使用我认为效率不高的注释。点击此处阅读更多信息:https://plotly.com/r/text-and-annotations/
## packages
library(shiny)
library(plotly)
library(dplyr)
library(tidyr)
## reading reactive to a variable
plot_data <- SWITCHING_SUMS_NET()
plot_data %>%
## rename variables to the names to be used in the plot
rename_at(c("V1", "V2", "V3", "V4"),
list(~c("Affordability", "Experience Change",
"Unavailability", "Attracted buy another brand"))) %>%
## reshape data from wide to long
pivot_longer(-week) %>%
## plot the rehsaped data
## add a trace for liens and markers with legend
plot_ly(x = ~week, y = ~value, color = ~name,
type = 'scatter', mode = 'lines+markers',
showlegend = T) %>%
## add a trace for text without legend
## insert `color = I("Black")` to have texts in one for all
add_text(text=~value, textposition="top center",
showlegend = F) %>%
## set the layout
layout(xaxis = list(title = ''),
yaxis = list (title = 'Count', showticklabels = T),
legend = list(orientation = 'h', xanchor = "center", x = 0.5, y = -0.3))示例:
我还添加了一个使用iris dataset的插图,因为您还没有共享数据。
library(dplyr)
library(tidyr)
library(plotly)
iris %>%
filter(Species == "setosa") %>%
slice(1:10) %>%
arrange(Sepal.Length) %>%
pivot_longer(-c(Species, Sepal.Length)) %>%
plot_ly(x=~Sepal.Length, y=~value, color = ~name,
type = 'scatter', mode = 'lines+markers',
showlegend = T) %>%
add_text(text=~value, textposition="top center",
showlegend = F) %>%
layout(xaxis = list(title = ''),
yaxis = list (title = 'Count', showticklabels = T),
legend = list(orientation = 'h', xanchor = "center", x = 0.5, y = -0.3))

https://stackoverflow.com/questions/62643187
复制相似问题