gpt4 book ai didi

r - ggplot : no color in plot

转载 作者:行者123 更新时间:2023-12-02 04:47:53 26 4
gpt4 key购买 nike

我正在尝试为我的 ggplot 添加颜色,但我似乎无法让它工作。我有一个 PlotAllLayers 函数,它会自动将我的 data.frame 中的所有内容添加到绘图中。现在我想添加“Dark2”调色板,但它似乎不起作用。

library(ggplot2)
x <- c(0:100)
df <- sapply(seq(5,100,by=10), function(n) dbinom(x,n,.6))
df <- data.frame(x,df)

plotAllLayers<-function(df){
p<-ggplot(data=df,aes(df[,1]))
for(i in names(df)[-1]){
p<-p+geom_line(aes_string(y=i))
}
return(p)
}

testplot <- plotAllLayers(df)
testplot <- testplot + scale_color_brewer(palette="Dark2")
print(testplot)

最佳答案

您在函数中迭代添加层的技术迫使您迭代分配颜色名称。这不是使用 ggplot 的规范方式。相反,首先融化你的数据,一切都会变得简单:

library(reshape2)
library(ggplot2)
# Melt your data:
melted.df<-melt(df,id.vars='x')
# x variable value
# 1 0 X1 0.01024
# 2 1 X1 0.07680
# 3 2 X1 0.23040

# Plot.
ggplot(melted.df,aes(x=x,y=value,colour=variable)) +
geom_line() +
scale_color_brewer(palette="Dark2")
# Warning that this palette doesn't support 10 colours.

关于r - ggplot : no color in plot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19444776/

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