[英]Link colour with integer ggplot2
我是ggplo2的新手,我無法重現我使用原生plot
功能的東西:基本上我迭代地將點添加到繪圖中,我希望新的點也可以迭代地添加顏色。
MWE:
pts = data.frame(x = rnorm(10), y = rnorm(10))
plot(pts, pch = 19)
for(i in 2:5) {
pts = data.frame(x = rnorm(10), y = rnorm(10))
points(pts, col = i, pch = 19)
}
而我用ggplot2:
pts = data.frame(x = rnorm(10), y = rnorm(10))
p <- ggplot(pts, aes(x,y)) + geom_point()
print(p)
for(i in 2:5) {
pts = data.frame(x = rnorm(10), y = rnorm(10))
p <- p + geom_point(data = pts, aes(colour = i))
print(p)
}
這並沒有給出同樣的東西。 我曾想過使用
scale_colour_hue(5)
代替aes(colour=i)
來指定我想要5種不同的可區分顏色,但是我收到了一個錯誤:
錯誤:提供給離散比例的連續值
謝謝 !
由於您的案例的迭代性質,這可能是一個解決方案。 我已將迭代添加到數據中,以獲取相關數據集中包含的某個點的所有信息。 然后我用factor(i)
給它着色。 你使用aes(color=i)
是正確的方式,但是當迭代結束時我等於5時,所有點都被着色為5(除了第一次迭代,因為它們沒有顏色映射。
編輯:創建一個列'迭代',其因子級別為1,每個數據集中的迭代次數,並強制所有級別顯示在scale參數中。
set.seed(124)
n_iterations <- 5
pts = data.frame(x = rnorm(10),
y = rnorm(10),
iteration=factor(1,levels=1:n_iterations)
)
p <- ggplot(pts, aes(x,y, color=iteration)) + geom_point()+
scale_colour_discrete(drop=FALSE) + #forces all levels to display
ylim(c(-2.5,2.5)) #keeps plot limits constant
for(i in 2:5) {
pts = data.frame(x = rnorm(10),
y = rnorm(10),
iteration=factor(i,levels=1:n_iterations))
p <- p + geom_point(data = pts)
print(p)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.