英文:
Is there any way to add 'custom' legend in R ggplot2?
问题
在R的ggplot2中是否有一种方法可以添加一个真正的“自定义”图例?
所有在线可用的说明似乎只介绍了如何修改原始数据中已存在的图例。
是否有可能添加一个自定义的图例,可以是任何形状和文字,这些在原始数据集中不存在?
data.frame(x = 1:5,
y = rnorm(5),
z = c('a', 'b', 'c', 'd', 'e')) %>%
ggplot(aes(x = x, y = y, fill = z)) + geom_point()
例如,如果我运行上面的代码,
它会生成上面的图像。
我想做的是,在原始数据集中不存在的情况下,添加一个填充为“红色”的圆圈,带有“ABCDE”图例。
英文:
Is there any way to add a truly 'custom' legend in R ggplot2?
All instructions available online seem to only introduce ways to modify the already existent legends from the original data.
Is it possible to add a custom legend, in any shape and and words, that do not exist in the original dataset?
data.frame(x = 1:5,
y = rnorm(5),
z = c('a', 'b', 'c' , 'd' , 'e')) %>%
ggplot(aes(x = x, y = y, fill = z)) + geom_point()
for example, if I run the code
it gives the above image.
What I would like to do is, add a circle filled with 'red' color that has 'ABCDE' legend, which is nonexistent in the original dataset.
答案1
得分: 1
I believe there are different ways to do this. One way to achieve your concrete goal would be to make "z" a factor with 'abcde' as a factor level (which does not appear in the data) and then use drop == FALSE
in the color scale.
dat <- data.frame(x = 1:5, y = rnorm(5), z = c('a', 'b', 'c' , 'd' , 'e'))
dat$z <- factor(dat$z, levels = c(letters[1:5], 'abcde'))
ggplot(dat, aes(x = x, y = y, color = z)) +
geom_point() +
scale_color_manual(values = c(rep("black",5), "red"), drop = FALSE)
英文:
I believe there are different ways to do this. One way to achieve you concrete goal would be to make z a factor with 'abcde' as a factor level (which does not appear in the data) and then use drop == FALSE
in the color scale.
dat <- data.frame(x = 1:5, y = rnorm(5), z = c('a', 'b', 'c' , 'd' , 'e'))
dat$z <- factor(dat$z, levels = c(letters[1:5], 'abcde'))
ggplot(dat, aes(x = x, y = y, color = z)) +
geom_point() +
scale_color_manual(values = c(rep("black",5), "red"), drop = FALSE)
答案2
得分: 1
And a second option would be to add an additional category via the limits
argument of the color scale, where for the latter I use scale_color_manual
as in the approach by @AndreasM:
set.seed(123)
dat <- data.frame(x = 1:5, y = rnorm(5), z = c("a", "b", "c", "d", "e"))
library(ggplot2)
ggplot(dat, aes(x = x, y = y, color = z)) +
geom_point() +
scale_color_manual(
values = c(rep("black", 5), "red"),
limits = function(x) c(x, "abcde")
)
英文:
And a second option would be to add an additional category via the limits
argument of the color scale, where for the latter I use scale_color_manual
as in the approach by @AndreasM:
set.seed(123)
dat <- data.frame(x = 1:5, y = rnorm(5), z = c("a", "b", "c", "d", "e"))
library(ggplot2)
ggplot(dat, aes(x = x, y = y, color = z)) +
geom_point() +
scale_color_manual(
values = c(rep("black", 5), "red"),
limits = \(x) c(x, "abcde")
)
<!-- -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论