gpt4 book ai didi

r - ggplot 图例顺序不匹配

转载 作者:行者123 更新时间:2023-12-02 09:24:29 25 4
gpt4 key购买 nike

我是 R/ggplot 的新手,我在 StackOverflow 上调查了 similar problems ,无济于事。这对于屋内的ggplot专家来说可能是一个小问题,如果是的话,我期待着快速的解答!

所以这里是:我正在尝试根据存储在数据框中的变量绘制 4 条曲线,同时使用颜色和线型。不幸的是,图例标签与曲线不匹配,这违背了图例的全部目的。

下图: 4 curves with mismatched labels

这是生成它的代码:

# declare variables
alpha = 0.5
m = 500
x = seq(m)
fdr_thresh = x/m*alpha
lvl_thresh = rep(alpha,m)
pvals = sin(2*pi*x/20)
pvalsA = exp(-x/100)*cos(2*pi*x/20)

# plot
df <- data.frame(pvals=pvals, pvalsA = pvalsA, FDR = fdr_thresh, level = lvl_thresh, x=x)
p4 <- ggplot(data = df) + geom_line(aes(x=x, y=pvals,color="Pure Sinusoid",linetype="Pure Sinusoid"))
p4 <- p4 + geom_line(aes(x=x, y=pvalsA,color="Damped Sinusoid",linetype="Damped Sinusoid"))
p4 <- p4 + geom_line(aes(x=x, y=FDR,color = 'FDR', linetype='FDR'))
p4 <- p4 + geom_line(aes(x=x, y=level,color='alpha',linetype='alpha'))
p4 = p4+ scale_linetype_manual(name = "Significance", values=c("Pure Sinusoid"= 1,"Damped Sinusoid" = 1,"FDR" = 2,"alpha" = 3),labels=c("Pure Sinusoid", "Damped Sinusoid", "Sloping line",bquote(alpha == .(alpha))))
p4 = p4 + scale_color_manual(name = "Significance",values=c("Pure Sinusoid"= "Chocolate1","Damped Sinusoid" = 'Chartreuse4',"FDR" = "black","alpha" = "black") , labels=c("Pure Sinusoid", "Damped Sinusoid", "Sloping line",bquote(alpha == .(alpha))))
p4 <- p4 + theme(legend.position = c(0.7, 0.8),legend.title=element_blank(),legend.key = element_rect(fill = "transparent",colour = "transparent"),legend.background = element_rect(fill=alpha('white', 0.8)))
show(p4)

如果能提供有关如何更好地执行此操作的提示,我将不胜感激。在 Matlab 或 Python 中绘制相同的图会是正确的并且需要 15 分钟,所以我一定是在某个地方做出了错误的决定。 (不,选择 R 并不是那个决定:这是我努力学习它的一部分)

最佳答案

做到这一点的“正确方法”是将您的数据集融入一个长数据框,然后让 ggplot 负责为您绘制多条线,而不是发出单独的 geom_line() 调用 ...

# plot
df <- data.frame(pvals, pvalsA, FDR = fdr_thresh, level = lvl_thresh, x)

mm <- reshape2::melt(df,id.var="x")
my.labs <- c("Pure Sinusoid","Damped Sinusoid","Sloping line",
bquote(alpha==.(alpha)))
p4 <- ggplot(data = mm, aes(x,value,colour=variable,linetype=variable)) +
geom_line()
p4 <- p4 + scale_linetype_manual(name="Significance",values=c(1,1,2,3),
labels=my.labs)
p4 <- p4 + scale_color_manual(name = "Significance",
values=c("Chocolate1",'Chartreuse4',"black","black"),
labels=my.labs)
p4 <- p4 + theme(legend.position = c(0.7, 0.8),
legend.title=element_blank(),
legend.key = element_rect(fill = "transparent",
colour = "transparent"),
legend.background = element_rect(fill=alpha('white', 0.8)))
show(p4)

enter image description here

(我已经在我工作的 R session 中设置了 theme_bw(),这就是灰色背景/网格线丢失的原因......)

关于r - ggplot 图例顺序不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38962700/

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