在下面的示例中,如何为 R 的plot_ly 中的图例添加标题?
mtcars %>% plot_ly(x = ~disp, y = ~mpg, color = ~factor(cyl), size = ~wt) %>% add_markers(
hoverinfo = "text",
text = ~paste("Displacement = ", disp, "\nMiles Per Gallon = ", mpg) ) %>% layout(title ="Custom Hover Text")
谢谢
此功能已包含在
layout
选项中的 legend
函数中。有一个名为 title
的子选项,您可以在其中提供包含文本的列表。
mtcars %>%
plot_ly(x = ~disp, y = ~mpg, color = ~factor(cyl), size = ~wt) %>%
add_markers(hoverinfo = "text",
text = ~paste("Displacement = ", disp, "\nMiles Per Gallon = ", mpg) ) %>%
layout(title = "Custom Hover Text",
legend = list(title = list(text = "<b>Cylinders</b>"))) # TITLE HERE
我知道的唯一方法是使用注释并将其添加到图中。像这样:
legendtitle <- list(yref='paper',xref="paper",y=1.05,x=1.1, text="Cylinders",showarrow=F)
mtcars %>% plot_ly(x = ~disp, y = ~mpg, color = ~factor(cyl), size = ~wt) %>%
add_markers( hoverinfo = "text",
text = ~paste("Displacement=",disp, "\nMiles Per Gallon = ", mpg)) %>%
layout(title ="Custom Hover Text", annotations=legendtitle )
产量:
放置图例标题有点棘手,不确定这个位置是否总是有效。
另一种方法当然是使用 ggplot 和 ggplotly,然后让 ggplot 弄清楚。
看看@mics 评论这里,关于图例标题似乎仍然存在一些困惑 - 所以让我们来揭开谜底:
一旦我们将因子传递给
plot_ly()
的颜色参数
color = ~factor(drat)
plotly 将创建一个图例(用于离散或分类数据),我们可以使用
layout()
来设置图例标题:
fig_discrete <- mtcars %>%
plot_ly(
type = "scatter",
mode = "markers",
x = ~ disp,
y = ~ mpg,
color = ~ factor(cyl),
size = ~ wt,
fill = "",
hoverinfo = "text",
text = ~ paste("Displacement = ", disp, "\nMiles Per Gallon = ", mpg)
) %>% layout(title = "Custom Hover Text", legend = list(title = list(text = "<b>Cylinders</b>")))
fig_discrete
# plotly_json(fig_discrete)
# navigate:
# layout.legend.title.text
但是,一旦我们将数字数据传递给
plot_ly()
的颜色参数
color = ~drat
plotly 将创建一个颜色条(用于连续数据),我们可以使用
colorbar()
来设置颜色条标题:
fig_continuous <- mtcars %>%
plot_ly(
type = "scatter",
mode = "markers",
x = ~ disp,
y = ~ mpg,
color = ~ drat,
marker = list(size = ~ wt * 3),
hoverinfo = "text",
text = ~ paste("Displacement = ", disp, "\nMiles Per Gallon = ", mpg)
) %>% layout(title = "Custom Hover Text") %>% colorbar(title = "<i>Rear Axle Ratio</i>")
fig_continuous
# plotly_json(fig_continuous)
# navigate:
# data[0].marker.colorbar.title
# and
# data[1].marker.colorbar.title
有关更多信息,请参阅相应文档。