英文:
ggplot - modifying the legend in case when using color and alpha
问题
考虑以下图表:
ggplot(ToothGrowth, aes(x = len,
color = factor(dose),
fill = factor(dose),
alpha = supp,
group = interaction(factor(dose), supp))) +
geom_density()
首先,图例似乎有点问题,因为它显示了supp
中的两个值的相同alpha
值。然而,这不是很重要。
我希望图例看起来像这样(在画图软件中创建):
请注意,我在这个手绘(用鼠标绘制的)图像中使用了空框作为低alpha的替代,实心框表示高alpha。
有人有任何关于如何处理这个问题的想法,或者如何可能编写代码来实现它吗?
我对图例中文本部分的放置没有强烈的意见。我主要关心的是拥有这个由六个彩色框组成的矩阵。
英文:
Consider the following plot:
ggplot(ToothGrowth, aes(x = len,
color = factor(dose),
fill = factor(dose),
alpha = supp,
group = interaction(factor(dose), supp))) +
geom_density()
First thing, the legend seems a bit wrong because it displays the same value of alpha
for both values in supp
. However, that's not so important.
I would like the legend to look like this (made in Paint):
Note that I used the empty box as a substitute for low alpha in this hand-drawn (mouse-drawn) image, and the filled box represents high alpha.
Does anyone have any idea on how to even approach this, or how would it be possible to code it?
I don't have strong feelings about the placement of the text parts in the legend. My central interest is to have this matrix of six colored boxes.
答案1
得分: 1
这是一个方法,我创建一个用于图例的绘图,然后将其合并进来。
legend_plot <- ggplot(data.frame(dose = factor(c(0.5, 1, 2)),
supp = rep(c("OJ", "VC"), each = 3)),
aes(x = supp, y = forcats::fct_rev(dose),
color = factor(dose),
fill = factor(dose),
alpha = supp,
group = interaction(factor(dose), supp))) +
geom_tile(linewidth = 1, height = 0.8, width = 0.8) +
scale_x_discrete(position = "top") +
guides(color = "none", fill = "none", alpha = "none") +
labs(y = "dose") +
theme_minimal(base_size = 16) +
theme(panel.grid = element_blank())
library(patchwork)
ggplot(ToothGrowth, aes(x = len,
color = factor(dose),
fill = factor(dose),
alpha = supp,
group = interaction(factor(dose), supp))) +
geom_density() +
guides(color = "none", fill = "none", alpha = "none") +
legend_plot +
plot_layout(design = "
1#
12
1#", widths = c(3,1))
英文:
Here's an approach where I make a plot for the legend and combine it in.
legend_plot <- ggplot(data.frame(dose = factor(c(0.5, 1, 2)),
supp = rep(c("OJ", "VC"), each = 3)),
aes(x = supp, y = forcats::fct_rev(dose),
color = factor(dose),
fill = factor(dose),
alpha = supp,
group = interaction(factor(dose), supp))) +
geom_tile(linewidth = 1, height = 0.8, width = 0.8) +
scale_x_discrete(position = "top") +
guides(color = "none", fill = "none", alpha = "none") +
labs(y = "dose") +
theme_minimal(base_size = 16) +
theme(panel.grid = element_blank())
library(patchwork)
ggplot(ToothGrowth, aes(x = len,
color = factor(dose),
fill = factor(dose),
alpha = supp,
group = interaction(factor(dose), supp))) +
geom_density() +
guides(color = "none", fill = "none", alpha = "none") +
legend_plot +
plot_layout(design = "
1#
12
1#", widths = c(3,1))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论