R - ggplot2 geom_area只有一个类别可见吗?

时间:2016-10-11 20:23:01

标签: r plot ggplot2

R的新手,对stackoverflow来说是新手,请原谅我......

我正在尝试使用ggplot2在R中制作时间序列图。我想显示两个线图,它们在给定日期的值之下填充。我一直试图用geom_area(position =“identity”)函数来做这件事。

但是,我的图表中只显示了一种颜色(尽管两者都显示在图例中)。我开始使用melt()融化我的数据,现在正在使用三列(X =时间,变量=地下水井,值=地下水位置)。下面是我的代码的简化版本,以及我得到的截图。

Bank01MWtest<-data.frame(X=(c(1,2,2,1)),variable=(c("MW-01A","MW-01A","MW-01B","MW-01B")),value=(c(576,571,584,580)))

ggplot(data=Bank01MWtest, aes(x=X, y=value,group=variable))+geom_area(position="identity", aes(fill=variable))+geom_line(aes(color=variable))+coord_cartesian(ylim=c(570,590))

我想要显示两种颜色。一种颜色低于MW.01A线,一种低于MW.01B线。

Elevation Data

Updated to be reproducible

任何帮助?

2 个答案:

答案 0 :(得分:1)

尝试使用geom_area,使用一些合成生成的Bank01MWtest数据集:

head(Bank01MWtest)
    Time variable    value
1 2016-07-01   MW-01A 582.5482
2 2016-07-02   MW-01A 580.5652
3 2016-07-03   MW-01A 582.3305
4 2016-07-04   MW-01A 583.3122
5 2016-07-05   MW-01A 576.3432
6 2016-07-06   MW-01A 584.4086

tail(Bank01MWtest)
        Time variable    value
195 2016-10-03   MW-01B 573.8355
196 2016-10-04   MW-01B 575.3218
197 2016-10-05   MW-01B 570.8007
198 2016-10-06   MW-01B 572.3415
199 2016-10-07   MW-01B 575.3291
200 2016-10-08   MW-01B 578.0055

ggplot(data=Bank01MWtest, aes(x=Time, y=value,group=variable))+
  geom_area(position='identity', aes(fill=variable), alpha=0.2)+
  scale_x_date(date_breaks= "1 month", date_minor_breaks = "15 days", date_labels = "%b", 
               limits = c(min(Bank01MWtest$Time),max(Bank01MWtest$Time))) +
  geom_line(aes(color=variable))+coord_cartesian(ylim=c(570,590))

enter image description here

答案 1 :(得分:0)

我相信geom_area正在被geom_ribbon中的ggplot2取代,所以我将在我的解决方案中使用后者。您还需要为此解决方案重新构建从长到宽的数据,为每个图例类别提供自己的列。我将使用dcast包中的reshape2函数执行此操作。

此处的想法是添加包含不同ymax变量的图层,使用fill选项指定图例标签,然后使用scale_fill_manual函数添加带颜色的图例。

library(ggplot2)
library(reshape2)

Bank01MWtest<-data.frame(X=sample(c(1,1,2,2)),
                     variable=sample(c("MW01A","MW01A","MW01B","MW01B")),
                     value=sample(c(576,571,584,580)))

### Note above I modified your category labels by getting rid of the "-" sign 
### so that they can be used as variable names below.

dat = dcast(Bank01MWtest, X~variable)

ggplot(data=dat, aes(x=X)) + 
  geom_ribbon(aes(ymin=0, ymax=MW01A, fill="MW01A")) + 
  geom_ribbon(aes(ymin=0, ymax=MW01B, fill="MW01B")) +
  scale_fill_manual("", values=c("green", "blue")) +
  coord_cartesian(ylim=c(570,590))