In Brief
我知道scale_*_*(drop = TRUE)
可用于从图例中删除空因子水平。也许违反直觉,我试图放弃used情节的水平。
正如您可能已经猜到的,这是一个稍微有点 hack 的用例:我使用隐形条geom_bar
抵消“浮动”的李克特反应可视化。我是not对框架挑战或解决此问题的替代方法感兴趣,我特别询问如何从图例中删除使用过的级别。
用例和示例
下面的代码重现了我的可视化的一个非常简单的版本。它工作得很好,但图例从中心稍微偏移(这在“真实”可视化中更明显)。我想放弃“看不见”的层面来呈现这一点。我知道我可以使用数字参数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")
Created on 2021-06-30 by the reprex package https://reprex.tidyverse.org (v2.0.0)