gpt4 book ai didi

r - stat_function 和图例 : create plot with two separate colour legends mapped to different variables

转载 作者:行者123 更新时间:2023-12-04 08:09:58 26 4
gpt4 key购买 nike

我想用 ggplot2 在一张图像中组合两种不同类型的图。这是我使用的代码:

fun.bar <- function(x, param = 4) {
return(((x + 1) ^ (1 - param)) / (1 - param))
}

plot.foo <- function(df, par = c(1.7, 2:8)) {
require(ggplot2)
require(reshape2)
require(RColorBrewer)
melt.df <- melt(df)
melt.df$ypos <- as.numeric(melt.df$variable)
p <- ggplot(data = melt.df, aes(x = value, y = ypos, colour = variable)) +
geom_point(position = "jitter", alpha = 0.2, size = 2) +
xlim(-1, 1) + ylim(-5, 5) +
guides(colour =
guide_legend("Type", override.aes = list(alpha = 1, size = 4)))
pal <- brewer.pal(length(par), "Set1")
for (i in seq_along(par)) {
p <- p + stat_function(fun = fun.bar,
arg = list(param = par[i]), colour = pal[i], size = 1.3)
}
p
}

df.foo <- data.frame(A=rnorm(1000, sd=0.25),
B=rnorm(1000, sd=0.25), C=rnorm(1000, sd=0.25))
plot.foo(df.foo)

结果,我得到了以下图片。
my_plot
但是,我想要另一个颜色从红色到粉红色的图例,在图的下部显示有关曲线参数的信息。问题是这两个部分的关键美学是颜色,因此通过 scale_colour_manual() 手动覆盖破坏现有的传说。

我知道有一个“一种美学 - 一种传奇”的概念,但是在这种特定情况下如何绕过这种限制?

最佳答案

我想分享一个我在等待这个问题的答案时使用的快速技巧。

fun.bar <- function(x, param = 4) {
return(((x + 1) ^ (1 - param)) / (1 - param))
}

plot.foo <- function(df, par = c(1.7, 2:8)) {
require(ggplot2)
require(reshape2)
require(RColorBrewer)
melt.df <- melt(df)
melt.df$ypos <- as.numeric(melt.df$variable)
# the trick is to override factor levels
levels(melt.df$variable) <- 1:nlevels(melt.df$variable)
p <- ggplot(data = melt.df, aes(x = value, y = ypos, colour = variable)) +
geom_point(position = "jitter", alpha = 0.2, size = 2) +
xlim(-1, 1) + ylim(-5, 5) +
guides(colour =
guide_legend("Type", override.aes = list(alpha = 1, size = 4)))
pal <- brewer.pal(length(par), "Set1")
for (i in seq_along(par)) {
p <- p + stat_function(fun = fun.bar,
arg = list(param = par[i]), colour = pal[i], size = 1.3)
}
# points are displayed by supplying values for manual scale
p + scale_colour_manual(values = pal, limits = seq_along(par), labels = par) +
# this needs proper "for" cycle to remove hardcoded labels
annotate("text", x = 0.8, y = 1, label = "A", size = 8) +
annotate("text", x = 0.8, y = 2, label = "B", size = 8) +
annotate("text", x = 0.8, y = 3, label = "C", size = 8)
}

df.foo <- data.frame(A=rnorm(1000, sd=0.25),
B=rnorm(1000, sd=0.25), C=rnorm(1000, sd=0.25))
plot.foo(df.foo)

enter image description here
这种解决方法甚至不如@Henrik 提供的答案那么棒,但适合我的一次性需求。

关于r - stat_function 和图例 : create plot with two separate colour legends mapped to different variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19219411/

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