如何从图例中删除已使用的值? [英] How can I drop a used value from the legend?
本文介绍了如何从图例中删除已使用的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简而言之
我知道scale_*_*(drop = TRUE)
可用于从图例中删除空因素级别。也许与直觉相反的是,我正在尝试从绘图中删除已用级别。
正如您可能已经猜到的,这是一个有点老套的用例:我在geom_bar
中使用不可见条来抵消"浮动"Likert响应的可视化效果。我对帧挑战或解决此问题的其他方法不感兴趣,我特别询问如何从图例中删除使用过的级别。
用例和示例
下面的代码重现了我的可视化的一个非常简单的版本。它工作得很好,但图例离中心的距离很小(这在真正的可视化中更值得注意)。我想把"看不见"的水平降下来来呈现这一点。我知道我可以使用数字参数legend.position
将整个事情重新居中,但这很麻烦,而且不能一概而论。
## libraries ---
require(ggplot2)
#> Loading required package: ggplot2
require(dplyr)
#> Loading required package: dplyr
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
## data ---
plotData <- tibble(label =
factor(c("", "strawberries", "blueberries", "", "strawberries", "blueberries"),
levels = c("strawberries", "blueberries", ""), ordered = TRUE),
value = c(30, 40, 20, 15, 30, 15),
bowl = factor(c("bowl1", "bowl1", "bowl1", "bowl2", "bowl2", "bowl2")))
## plot ---
### Specs for the legend
legendSpecs <- guide_legend(nrow = 1, label.position = "bottom",
reverse = TRUE, title = NULL)
### desired plot
ggplot(plotData, aes(x = value, y = bowl,
fill = label, colour = label)) +
geom_bar(stat = "identity", position = "stack") +
scale_fill_manual(values = c("blue", "red", NA), guide = legendSpecs) +
scale_colour_manual(values = c("black", "black", NA), guide = legendSpecs) +
theme_minimal() +
theme(legend.position = "bottom")
演示我要删除的图例中的小偏移量:
### demonstrating legend offset
ggplot(plotData, aes(x = value, y = bowl,
fill = label, colour = label)) +
geom_bar(stat = "identity", position = "stack") +
scale_fill_manual(values = c("blue", "red", NA), guide = legendSpecs) +
scale_colour_manual(values = c("black", "black", "black"), guide = legendSpecs) +
theme_minimal() +
theme(legend.position = "bottom")
由reprex package(v2.0.0)在2021-06-30创建
推荐答案
这可以通过将刻度的breaks
设置为仅包括所需类别来实现:
## libraries ---
require(ggplot2)
require(dplyr)
## data ---
plotData <- tibble(label =
factor(c("", "strawberries", "blueberries", "", "strawberries", "blueberries"),
levels = c("strawberries", "blueberries", ""), ordered = TRUE),
value = c(30, 40, 20, 15, 30, 15),
bowl = factor(c("bowl1", "bowl1", "bowl1", "bowl2", "bowl2", "bowl2")))
## plot ---
### Specs for the legend
legendSpecs <- guide_legend(nrow = 1, label.position = "bottom",
reverse = TRUE, title = NULL)
### desired plot
ggplot(plotData, aes(x = value, y = bowl,
fill = label, colour = label)) +
geom_bar(stat = "identity", position = "stack") +
scale_fill_manual(values = c("blue", "red", NA), na.value = NA,
guide = legendSpecs, breaks = c("blueberries", "strawberries")) +
scale_colour_manual(values = c("black", "black", NA), , na.value = NA,
guide = legendSpecs,
breaks = c("blueberries", "strawberries")) +
theme_minimal() +
theme(legend.position = "bottom")
这篇关于如何从图例中删除已使用的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文