【发布时间】:2020-03-19 18:14:51
【问题描述】:
我想用颜色和形状美学绘制数据。这很好用,但是我正在努力制作一个不错的传奇。
这是一个使用 mtcars 数据集的 MWE。数据操作对于重新处理我正在处理的数据集是必要的。变量 cylindex 是人工创建的,以允许在圆柱编号上进行颜色填充,并为该类别中的每个观测值具有不同的形状。变量 car 是我理想的用作图例标签的对象。
library(tidyverse)
library(plotly)
data(mtcars)
mtcars <- mtcars[c(1,3,4,5,8,30),c("cyl","disp","hp")] %>%
as_tibble(rownames="car") %>%
group_by(cyl) %>%
mutate(cylindex=rank(cyl,ties.method="first")) %>%
ungroup() %>%
# removed because 'car' is available from the row name
# but this was used in the original question and one answer
#mutate(brand=letters[1:nrow(.)]) %>%
mutate_at(c("cyl","cylindex"),as_factor) %>%
mutate(legend=paste(cyl,cylindex,sep=" - "))
mtcars %>%
ggplot(aes(x=disp, y=hp, color=cyl, shape=cylindex)) +
geom_point(size=10) -> g
print(g)
ggplotly(g)
mtcars %>%
ggplot(aes(x=disp, y=hp, color=legend, shape=legend)) +
geom_point(size=10) +
scale_color_manual(values=c("red","red","blue","blue","blue","green")) +
scale_shape_manual(values=c(16,17,16,17,15,16))
使用 ggplotly 至少结合了图例,但是我很难将标签自动更改为相应的汽车。
使用来自@dc37 的答案,我设法生成了类似于 ggplotly 的图例,但以硬编码的方式。我在每个条目旁边写下了我想要的图例标签。该信息来自从行名称添加的汽车列。
我该怎么做
- 将两个图例与 ggplot2 结合(类似于 ggploty),无需对数据量进行硬编码
- 将图例标签自动更改为另一个变量中的值(本例中为品牌)
非常感谢您的帮助。
【问题讨论】:
-
说实话不是这个,谢谢指点。它与@dc37 的答案方向相同。