点和线不会连接

时间:2013-12-09 12:45:02

标签: r ggplot2

我正在尝试连接我的情节中的点并尝试geom_point() + geom_line(),但它无效。

下面的代码只是为了点。有没有人知道为什么geom_line()没有添加任何行?

DensityE = read.csv("DensityElk.csv", header = TRUE)
str(DensityE)

DensityE$Date <- factor(DensityE$Date, levels=
        c("20-May","3-Jun",
      "17-Jun","1-Jul","16-Jul", 
      "22-Jul", "15-Aug"), order=TRUE)

ggplot(data=DensityE, aes(Date,Density)) + 
geom_point(aes(shape = factor(Genus)), size = 4, 
position="jitter") + 
theme_bw() + xlab("Date") +
ylab("Density per m2") + ggtitle("COP 1992") +
opts(legend.key = theme_blank()) + 
opts (legend.title = theme_blank())+
opts(legend.text = theme_text(size=9))

1 个答案:

答案 0 :(得分:4)

因为您在x轴上使用了因子(Date),ggplot2不会自动连接x值之间的线。两个解决方案是(1)geom_line(aes(group=Genus))或(2)geom_line(aes(x=as.numeric(Date)))

构建数据框:

DensityE <- data.frame(
    Date=c("1-Jul","16-Jul","22-Jul","3-Jun","17-Jun"),
    Genus=c("Epeorus","Epeorus","Epeorus","Rhyacophila","Rhyacophila"),
    Density=c(3.5,3.25,1,1,0.75))

制作情节:我做了一些改变

  • theme_blank更改为element_blank,将opt更改为theme,以便与最近的ggplot2版本保持一致
  • 删除了抖动 - 如果您想要连接相同点的抖动点和线,则必须手动将抖动添加到y值。

代码:

 library(ggplot2)
 ggplot(data=DensityE, aes(Date,Density)) + 
    geom_point(aes(shape = factor(Genus)), size = 4)+
    geom_line(aes(group=Genus))+
 theme_bw() + xlab("Date") +
 ylab("Density per m2") + ggtitle("COP 1992") +
 theme(legend.key = element_blank()) + 
 theme(legend.title = element_blank())+
 theme(legend.text = element_text(size=9))

enter image description here