gpt4 book ai didi

r - 图例中的符号和颜色分开

转载 作者:行者123 更新时间:2023-12-03 16:18:35 25 4
gpt4 key购买 nike

我想用plotly实现与此ggplot代码相同的结果:

mtcars %>% add_rownames('car') %>% 
ggplot(aes(x = mpg,
y = disp,
color = as.factor(gear),
shape = as.factor(cyl))) +
geom_point()

结果是:
ggplot version

我的密谋代码是:
library(dplyr)
mtcars %>% add_rownames('car') %>%
plot_ly(x = ~mpg,
y = ~disp,
text = ~car,
color = ~as.factor(gear),
symbol = ~as.factor(cyl),
mode = 'markers')

列举了图例中颜色和形状的所有可能组合。
enter image description here

有没有办法让ggplot具有相似的图例?

最佳答案

更新:要克服我以前的解决方案中提到的一些问题(请参见下文)并提高图例的可用性,可以简单地将列名称添加到图例描述中,然后将图例组分配给每个类别。

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的答案,我们可以手动创建 cylindersgears的组。随后,有了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"))

Unresolved 问题:
  • 必须手动创建组
  • 组仅被覆盖(颜色超过形状)。这意味着只能在图例中禁用/激活整个组(例如,不可能仅显示具有4个柱面的条目)
  • 第二个图例标题(注释)的位置取决于 plotly 的高度!
  • 关于r - 图例中的符号和颜色分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47539539/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com