我尝试使用split参数在plot_ly中创建一个散点图,但是我对图例和传感器有一些困难。格式。具体来说,一旦我向图表添加标签,图例中就会添加更多项目,颜色不匹配,我只需点击一下即可关闭整个系列。这是一个例子:
library(plotly)
plot_ly(mtcars,
type = "scatter",
x = ~hp,
y =~qsec,
split = ~cyl,
text = rownames(mtcars)) %>%
add_text(textposition = "middle right")
运行此代码时,您可以看到每个点都显示标签,但它们以随机颜色显示。此外,图例有6个项目。我想要的是:
非常感谢您的帮助!
如果有帮助:
答案 0 :(得分:1)
使用类型mode
时,您需要设置scatter
。使用markers+text
选项,我相信您无法单独为文本着色。如果您不介意文本是灰色的,解决方案是:
plot_ly(mtcars,
type = "scatter",
x = ~hp,
y = ~qsec,
split = ~cyl,
mode = "markers+text",
text = rownames(mtcars),
textposition = "middle right")
如果您想让它与您的请求100%匹配,则会变得更加复杂,您无法使用split
参数。
您必须为每个柱面级别创建单独的轨迹,首先使用mutate
明确包含行名称。然后,您可以使用filter
为每个柱面级别mtcars
进行子集化。对于每个级别,创建2个跟踪,标记和文本。然后,color
将等于cyl
的因子级别。最后,您必须为图例中的每个圆柱分组,隐藏您不需要的条目。
library(plotly)
library(dplyr)
plot_ly(filter(mutate(mtcars, names = rownames(mtcars)), cyl == 4),
type = "scatter",
x = ~hp,
y = ~qsec,
mode = "markers",
color = ~factor(cyl, c(4,6,8)),
legendgroup = '4',
name = '4',
textposition = "middle right") %>%
add_trace(data = filter(mutate(mtcars, names = rownames(mtcars)), cyl == 4),
type = "scatter",
x = ~hp+2,
y = ~qsec,
color = ~factor(cyl, c(4,6,8)),
mode = "text",
text = ~names,
legendgroup = '4',
name = '4',
showlegend = FALSE,
textposition = "middle right") %>%
add_trace(data = filter(mutate(mtcars, names = rownames(mtcars)), cyl == 6),
type = "scatter",
x = ~hp,
y = ~qsec,
mode = "markers",
color = ~factor(cyl, c(4,6,8)),
legendgroup = '6',
name = '6',
textposition = "middle right") %>%
add_trace(data = filter(mutate(mtcars, names = rownames(mtcars)), cyl == 6),
type = "scatter",
x = ~hp+2,
y = ~qsec,
mode = "text",
color = ~factor(cyl, c(4,6,8)),
text = ~names,
legendgroup = '6',
name = '6',
showlegend = FALSE,
textposition = "middle right") %>%
add_trace(data = filter(mutate(mtcars, names = rownames(mtcars)), cyl == 8),
type = "scatter",
x = ~hp,
y = ~qsec,
mode = "markers",
color = ~factor(cyl, c(4,6,8)),
legendgroup = '8',
name = '8',
textposition = "middle right") %>%
add_trace(data = filter(mutate(mtcars, names = rownames(mtcars)), cyl == 8),
type = "scatter",
x = ~hp+2,
y = ~qsec,
mode = "text",
color = ~factor(cyl, c(4,6,8)),
text = ~names,
legendgroup = '8',
name = '8',
showlegend = FALSE,
textposition = "middle right")