我希望使用plotly:
获得与此ggplot代码相同的结果mtcars %>% add_rownames('car') %>%
ggplot(aes(x = mpg,
y = disp,
color = as.factor(gear),
shape = as.factor(cyl))) +
geom_point()
我的情节代码是:
library(dplyr)
mtcars %>% add_rownames('car') %>%
plot_ly(x = ~mpg,
y = ~disp,
text = ~car,
color = ~as.factor(gear),
symbol = ~as.factor(cyl),
mode = 'markers')
有没有办法让ggplot有类似的传奇?
答案 0 :(得分:3)
更新:为了克服我之前的解决方案中提到的一些问题(见下文)并增加图例的可用性,可以简单地将列名添加到图例说明中,然后分配每个类别的图例组。
mtcars %>% rownames_to_column('car') %>%
plot_ly() %>%
#Plot symbols for cyl
add_trace(type = "scatter",
x = ~mpg,
y = ~disp,
text = ~car,
symbol = ~paste0(cyl," cyl."),
mode = 'markers',
marker = list(color = "grey", size = 15)) %>%
#Overlay color for gears
add_trace(type = "scatter",
x = ~mpg,
y = ~disp,
text = ~car,
color = ~paste0(gear, " gears"),
mode = 'markers')
这是之前的解决方案,它在视觉上更接近ggplot2等价物:
根据this thread中dww的回答,我们可以手动为cylinders
和gears
创建群组。随后,通过Artem Sokolov this thread的答案,我们可以添加图例标题作为注释。
mtcars %>% rownames_to_column('car') %>%
plot_ly() %>%
#Plot symbols for cyl
add_trace(type = "scatter",
x = ~mpg,
y = ~disp,
text = ~car,
symbol = ~as.factor(cyl),
mode = 'markers',
legendgroup="cyl",
marker = list(color = "grey", size = 15)) %>%
#Overlay color for gears
add_trace(type = "scatter",
x = ~mpg,
y = ~disp,
text = ~car,
color = ~as.factor(gear),
mode = 'markers',
legendgroup="gear") %>%
#Add Legend Titles (manual)
add_annotations( text="Cylinders:", xref="paper", yref="paper",
x=1.02, xanchor="left",
y=0.9, yanchor="bottom", # Same y as legend below
legendtitle=TRUE, showarrow=FALSE ) %>%
add_annotations( text="Gears:", xref="paper", yref="paper",
x=1.02, xanchor="left",
y=0.7, yanchor="bottom", # Y depends on the height of the plot
legendtitle=TRUE, showarrow=FALSE ) %>%
#Increase distance between groups in Legend
layout(legend=list(tracegroupgap =30, y=0.9, yanchor="top"))
未解决的问题: