[英]ggplot add horizontal line to grouped categorical data and share legend
这是一些制作分类条形图并在图表上放置平均线的代码。 问题是图例是分开的,我不知道如何将它们粘在一起。 我想我过去制作了一个虚拟变量并将其包含在 scale_manual arguments 但 geom_vline 不处理“填充”映射。 有任何想法吗?
library(tidyverse)
data(mtcars)
y = mean(mtcars$mpg)
x = unique(mtcars$cyl)
meanDf <-
data.frame(x, y )
mtcars$mean = y
mtcars$group = "mean"
mtcars %>%
ggplot(aes(x = factor(cyl), y = mpg, fill = factor(carb))) +
geom_col(position = "dodge") +
geom_hline(data = meanDf, aes(yintercept = y, color = "")) +
scale_fill_manual(name = "", values = c("blue", "red", "green", "white", "black", "yellow"), labels = paste("myLabel", 1:6)) +
scale_color_manual(name = "", values = "red", label = "myLabel") +
theme(panel.background = element_rect(fill = "white")) +
theme(legend.background = element_rect(color = "black", fill = "white"))
我认为为了可读性,最好将它们分开。 但是,出于格式化目的,您可以通过删除legend.title
(不仅仅是为其分配一个空字符串)并调整legend.margin
和legned.spacing
来使它们尽可能接近。 例如,
library(tidyverse)
data(mtcars)
y = mean(mtcars$mpg)
x = unique(mtcars$cyl)
meanDf <-
data.frame(x, y )
mtcars$mean = y
mtcars$group = "mean"
mtcars %>%
ggplot(aes(x = factor(cyl), y = mpg, fill = factor(carb))) +
geom_col(position = "dodge") +
geom_hline(data = meanDf, aes(yintercept = y, color = "")) +
scale_fill_manual(name = "", values = c("blue", "red", "green", "white", "black", "yellow"), labels = paste("myLabel", 1:6)) +
scale_color_manual(name = "", values = "red", label = "myLabel") +
theme(
legend.title = element_blank(),
legend.margin = margin(t = 0, b = 0, r = 2, l = 2),
legend.spacing.y = unit(.5, "pt")
)
一种选择是仅使用fill
比例并使用自定义键字形。
geom_hline
的颜色设置为参数,而不是在color
aes 上进行映射。 取而代之的是 map fill
aes 上的常量,例如""
。 缺点是我们会收到警告。scale_fill_manual
。geom_hline
的键字形,我使用了一个自定义键字形,它有条件地在draw_key_path
和geom_col
的默认键字形之间切换fill
颜色。 为了完成这项工作,我使用"red2"
作为线的附加填充颜色,我在自定义键字形 function 内切换为"red"
。library(tidyverse)
data(mtcars)
y = mean(mtcars$mpg)
x = unique(mtcars$cyl)
meanDf <- data.frame(x, y )
mtcars$mean = y
mtcars$group = "mean"
draw_key_cust <- function(data, params, size) {
if (data$fill %in% c("red2")){
data$colour <- "red"
data$fill <- NA
draw_key_path(data, params, size)
} else
GeomCol$draw_key(data, params, size)
}
mtcars %>%
ggplot(aes(x = factor(cyl), y = mpg, fill = factor(carb))) +
geom_hline(data = meanDf, aes(yintercept = y, fill = ""), color = "red") +
geom_col(key_glyph = "cust") +
scale_fill_manual(name = NULL, values = c("red2", "blue", "red", "green", "white", "black", "yellow"), labels = c("label", paste("myLabel", 1:6))) +
theme(panel.background = element_rect(fill = "white")) +
theme(legend.background = element_rect(color = "black", fill = "white"))
#> Warning: Ignoring unknown aesthetics: fill
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.