gpt4 book ai didi

r - 如何在ggplot中为每个方面添加图例?

转载 作者:行者123 更新时间:2023-12-04 10:45:53 27 4
gpt4 key购买 nike

我有以下 data.frame。我想绘制一个具有三个图例表的 ggplot,大小的通用图例,以及 var = "A"和 var = "B"的两个单独图例,从“值”列中获取值,这两个图例应放在旁边每个相关图。到目前为止,我已经尝试过为“var”列创建单个图例。

df <- data.frame(var = c("A","A","B","B"),
value = c("u","v","x","y"),
point = 1:4,
size = 1:4)

ggplot() +geom_point(data = df,
aes(x = point,y = NA,
color = value,size = size)) +
facet_grid(rows = vars(var))

谢谢。

编辑:
我附上了@Tung 建议的预期输出
enter image description here

最佳答案

这样的事情怎么样:

library(gridExtra)
library(ggplot2)
# split data for each "facet"
df <- split(df,f = df$var)

# plot for the first "facet"
p1 <- ggplot(df$A,aes(x = point,y = NA,colour = value, size = size)) +
geom_point() +
facet_wrap(~var, ncol=1) +
# here you set the axis
scale_x_continuous(limits = c(0.5, 4.5))

# do it for each "facet"
p2 <- p1 %+% df$B

# here the plot
grid.arrange(p1,p2)

enter image description here

关于r - 如何在ggplot中为每个方面添加图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53258299/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com