r - ggplot2 - 关闭与另一个几何图形具有相同美感的几何图形的图例

标签 r ggplot2

我正在用两个不同的几何图形绘制一个图,都使用填充。我希望一个 geom 有一个传奇,但另一个没有。但是添加 show.legend=F到所需的 geom 不会关闭该 geom 的图例。

示例:

library(tidyverse)
library(ggalluvial)

x = tibble(qms = c("grass", "cereal", "cereal"),
           move1 = "Birth",
           move2 = c("Direct", "Market", "Slaughter"),
           move3 = c("Slaughter", "Slaughter", NA),
           freq = c(10, 5, 7))

x %>% 
  mutate(id = qms) %>% 
  to_lodes_form(axis = 2:4, id = id) %>% 
  na.omit() %>% 
  ggplot(aes(x = x, stratum = stratum, alluvium = id,
             y = freq, label = stratum)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow(aes(fill = qms)) +
  geom_stratum(aes(fill = stratum), show.legend=F) +
  geom_text(stat = "stratum", size = 3) +
  theme_void() +
  labs(fill="")

输出:

Output from code

所需输出:

Desired output

问题:

如何关闭一个几何图形的填充图例,而不是另一个几何图形?我可以(如果必须的话)在inkscape/gimp 中执行此操作,但更喜欢我可以进行版本控制的解决方案。

最佳答案

看看最后一行代码:

scale_fill_discrete(breaks = c("grass", "cereal")) 

这将填充的中断定义为仅包括 cerealgrass , 按要求。

library(tidyverse)
library(ggalluvial)

x = tibble(qms = c("grass", "cereal", "cereal"),
           move1 = "Birth",
           move2 = c("Direct", "Market", "Slaughter"),
           move3 = c("Slaughter", "Slaughter", NA),
           freq = c(10, 5, 7))

x %>% 
  mutate(id = qms) %>% 
  to_lodes_form(axis = 2:4, id = id) %>% 
  na.omit() %>% 
  ggplot(aes(x = x, stratum = stratum, alluvium = id,
             y = freq, label = stratum)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow(aes(fill = qms)) +
  geom_stratum(aes(fill = stratum), show.legend=FALSE) +
  geom_text(stat = "stratum", size = 3) +
  theme_void() +
  labs(fill="") +
  scale_fill_discrete(breaks = c("grass", "cereal")) #<- This line!



创建于 2019-03-18 由 reprex package (v0.2.1)

关于r - ggplot2 - 关闭与另一个几何图形具有相同美感的几何图形的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55219669/

相关文章:

R中多列的每行排名

r - 将来自不同数据框的列添加到交叉表

r - 在环境中分配列表属性

r - 有没有一种方法可以指定 geom_raster 插值范围?

r - 如何重新排列分组条形图中的组

r - 控制每轴 ggplot2 裁剪

r - 在 R 基础图形或 ggplot 中使用动画散点图可能会发光吗?

r - GLM 回归预测——了解哪个因素水平是成功的

r - 如何在 R 中绘制拷贝数变异曲线?

r - view_zoom_manual xmin 和 xmax 使用日期 r ggplot