R 带有颜色和图例的简单ggplot2情况
尝试使用ggplot2绘制一些绘图,但无法理解aes中定义的颜色是如何工作的。与审美长度的错误作斗争 我尝试过在两个主要的ggplot调用aes中定义颜色以给出图例,但也在geom_线aes中定义颜色R 带有颜色和图例的简单ggplot2情况,r,ggplot2,colors,R,Ggplot2,Colors,尝试使用ggplot2绘制一些绘图,但无法理解aes中定义的颜色是如何工作的。与审美长度的错误作斗争 我尝试过在两个主要的ggplot调用aes中定义颜色以给出图例,但也在geom_线aes中定义颜色 # Define dataset: number<-rnorm(8,mean=10,sd=3) species<-rep(c("rose","daisy","sunflower","iris"),2) year<-c("1995","1995","1995","1995","19
# 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
#定义数据集:
数字以下是@kath的评论作为解决方案。开始学习是很微妙的,但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()
你确定第一个情节很好吗?我认为它分配了错误的组。一般问题是您在aes
之外定义group=species
,因此它采用的是向量species
,而不是d.flowers
的列。尝试例如geom_line(aes(group=species))
或将group=species
添加到ggplot
-调用另一个问题是,您使用cbind
将数据转换为字符矩阵,然后使用as.data.frame
将它们转换为因子。最好使用data.frame(数字、种类、年份)
。
#note geom_point() doesn't need to be grouped - try:
ggplot(data = d.flowers, aes(x = year,y = number, colour = species)) + geom_point()