[英]Simple ggplot2 situation with colors and legend
試圖用 ggplot2 繪制一些圖,但無法弄清楚 aes 中定義的顏色是如何工作的。 與審美長度的錯誤作斗爭。
我已經嘗試在主 ggplot 調用 aes 中定義顏色以給出圖例,但也在 geom_line aes 中定義顏色。
# Define dataset:
number<-rnorm(8,mean=10,sd=3)
species<-rep(c("rose","daisy","sunflower","iris"),2)
year<-c("1995","1995","1995","1995","1996","1996","1996","1996")
d.flowers<-cbind(number,species,year)
d.flowers<-as.data.frame(d.flowers)
#Plot with no colours:
ggplot(data=d.flowers,aes(x=year,y=number))+
geom_line(group=species) # Works fine
#Adding colour:
#Defining aes in main ggplot call:
ggplot(data=d.flowers,aes(x=year,y=number,colour=factor(species)))+
geom_line(group=species)
# Doesn't work with data size 8, asks for data of size 4
ggplot(data=d.flowers,aes(x=year,y=number,colour=unique(species)))+
geom_line(group=species)
# doesn't work with data size 4, now asking for data size 8
第一個圖給出了錯誤:美學必須是長度為 1 或與數據相同 (4):組
第二個給出錯誤:美學必須是長度為1或與數據相同(8):x,y,顏色
所以我很困惑 - 當給定長度為 4 或 8 的 aes 時,它不高興!
我怎么能更清楚地思考這個問題?
這是@kath提供的解決方案。 剛開始學習是很微妙的,但是aes()內部或外部的內容是關鍵。 一些更多信息- 審美何時會在aes()內部或外部出現? 以及許多優質的可谷歌搜索的“ ggplot美學”中心頁面,其中包含許多示例,可以剪切和嘗試。
library(ggplot2)
number <- rnorm(8,mean=10,sd=3)
species <- rep(c("rose","daisy","sunflower","iris"),2)
year <- c("1995","1995","1995","1995","1996","1996","1996","1996")
d.flowers <- data.frame(number,species,year, param1, param2)
head(d.flowers)
#number species year
#1 8.957372 rose 1995
#2 7.145144 daisy 1995
#3 9.864917 sunflower 1995
#4 7.645287 iris 1995
#5 4.996174 rose 1996
#6 8.859320 daisy 1996
ggplot(data = d.flowers, aes(x = year,y = number,
group = species,
colour = species)) + geom_line()
#note geom_point() doesn't need to be grouped - try:
ggplot(data = d.flowers, aes(x = year,y = number, colour = species)) + geom_point()
另外,您可以在沒有group()
情況下嘗試:
library(ggplot2)
number <- rnorm(8,mean=10,sd=3)
species <- rep(c("rose","daisy","sunflower","iris"),2)
year <- rep(c(1995,1996), each = 4)
d.flowers <- data.frame(number,species,year)
rm(number, species, year)
ggplot(data = d.flowers, aes(x = year,y = number,
colour = species)) + geom_line()
:另外,我也將消除向量number
, species
和year
使用前ggplot
之前,從全球環境ggplot
,通過@kath的建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.