R Plotly - 在散点图中向参考线添加注释
R Plotly - Add annotation to reference line in a scatter plot
我使用 iris 数据集在 R 中使用 Plotly 创建了一个散点图,并添加了两条参考线,一条在 x 轴上表示平均值 Sepal.Width,另一条在 y 轴上表示平均值Sepal.Length.
下面是可执行的 R 代码:
library(dplyr)
library(plotly)
iris <- datasets::iris
scatterplot <- plot_ly(data = iris, x = ~Sepal.Width, y = ~Sepal.Length, type = 'scatter',
text = ~Species,
color = I('orange')) %>%
layout(shapes=list(list(type = 'line',
x0 = mean(iris$Sepal.Width),
x1 = mean(iris$Sepal.Width),
y0 = 4,
y1 = 8,
line = list(width = 2)),
list(type = 'line',
x0 = 1.5,
x1 = 5,
y0 = mean(iris$Sepal.Length),
y1 = mean(iris$Sepal.Length),
line = list(width = 2))))
scatterplot
上面的 R 代码生成以下内容
Plotly output
我想为两条参考线(“平均萼片宽度”和“平均萼片长度”)添加注释文本(即标签)。
我遇到了 但是那里提到的解决方案对我不起作用。如果有人可以向我提供带有代码的解决方案,那将不胜感激。
PS:我正在使用 Plotly 4.8.0 版
下面的代码解决了我的问题。希望对大家有帮助。
library(dplyr)
library(plotly)
iris <- datasets::iris
scatter <- plot_ly(data = iris, x = ~Sepal.Width, y = ~Sepal.Length, type = 'scatter',
text = ~Species,
color = I('orange')) %>%
layout(shapes=list(list(type = 'line',
x0 = mean(iris$Sepal.Width),
x1 = mean(iris$Sepal.Width),
y0 = 4,
y1 = 8,
line = list(width = 2)),
list(type = 'line',
x0 = 1.5,
x1 = 5,
y0 = mean(iris$Sepal.Length),
y1 = mean(iris$Sepal.Length),
line = list(width = 2))),
annotations = list(list(
x = 3.4,
y = 7.9,
xref = 'x',
yref = 'y',
text = 'Mean Sepal Width',
showarrow = FALSE
),
list(
x = 4.7,
y = 5.6,
xref = 'x',
yref = 'y',
text = 'Mean Sepal Length',
showarrow = FALSE
)))
scatter
我使用 iris 数据集在 R 中使用 Plotly 创建了一个散点图,并添加了两条参考线,一条在 x 轴上表示平均值 Sepal.Width,另一条在 y 轴上表示平均值Sepal.Length.
下面是可执行的 R 代码:
library(dplyr)
library(plotly)
iris <- datasets::iris
scatterplot <- plot_ly(data = iris, x = ~Sepal.Width, y = ~Sepal.Length, type = 'scatter',
text = ~Species,
color = I('orange')) %>%
layout(shapes=list(list(type = 'line',
x0 = mean(iris$Sepal.Width),
x1 = mean(iris$Sepal.Width),
y0 = 4,
y1 = 8,
line = list(width = 2)),
list(type = 'line',
x0 = 1.5,
x1 = 5,
y0 = mean(iris$Sepal.Length),
y1 = mean(iris$Sepal.Length),
line = list(width = 2))))
scatterplot
上面的 R 代码生成以下内容 Plotly output
我想为两条参考线(“平均萼片宽度”和“平均萼片长度”)添加注释文本(即标签)。
我遇到了
PS:我正在使用 Plotly 4.8.0 版
下面的代码解决了我的问题。希望对大家有帮助。
library(dplyr)
library(plotly)
iris <- datasets::iris
scatter <- plot_ly(data = iris, x = ~Sepal.Width, y = ~Sepal.Length, type = 'scatter',
text = ~Species,
color = I('orange')) %>%
layout(shapes=list(list(type = 'line',
x0 = mean(iris$Sepal.Width),
x1 = mean(iris$Sepal.Width),
y0 = 4,
y1 = 8,
line = list(width = 2)),
list(type = 'line',
x0 = 1.5,
x1 = 5,
y0 = mean(iris$Sepal.Length),
y1 = mean(iris$Sepal.Length),
line = list(width = 2))),
annotations = list(list(
x = 3.4,
y = 7.9,
xref = 'x',
yref = 'y',
text = 'Mean Sepal Width',
showarrow = FALSE
),
list(
x = 4.7,
y = 5.6,
xref = 'x',
yref = 'y',
text = 'Mean Sepal Length',
showarrow = FALSE
)))
scatter