2013-08-29 101 views
2

使用下面的数据帧:ggplot图例键颜色和物品

ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+ 
    geom_area(data=sdf[sdf$machine=="A",])+ 
    geom_area(data=sdf[sdf$machine=="B",])+ 
    geom_area(data=sdf[sdf$machine=="C",]) 

ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+ 
    geom_area(position="dodge") 

enter image description here

然而,当:

sdf<-data.frame(hours=gl(n=3,k=1,length=9,labels=c(0,2,4)),  
       count=c(4500,1500,2600,4000,800,200,1500,50,20), 
       machine=gl(n=3,k=3,length=9,labels=c("A","B","C"))) 

下图可以使用任一这些脚本来生产填充颜​​色被改变,图例中的项目消失。

ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+ 
    geom_area(data=sdf[sdf$machine=="A",])+ 
    geom_area(data=sdf[sdf$machine=="B",],fill="darkorchid")+ 
    geom_area(data=sdf[sdf$machine=="C",]) 

enter image description here

理想的情况下,传说应该显示的颜色变化。

问题:哪个脚本可以在图例中创建项目以及为这些项目提供颜色控件?

回答

5

您可以使用scale_ X _manual(values=(无论))调整分配给任何美学的值。在这里你想要scale_fill_manual

ggplot(data=sdf,aes(x=hours,y=count,group=machine,fill=machine))+ 
    geom_area(position="dodge") + 
    scale_fill_manual(values=c("red", "darkorchid", "green")) 

enter image description here

需要注意的是,作为一项规则,你想让ggplot组为您的数据,你在你的第二个电话ggplot都做(这是group说法做什么)。分别提供每个“切片”数据,就像您在第一个示例中所做的那样,几乎违背了ggplot2的目的,应该避免。

+0

所以谢谢你回答这个问题!我可能会提出另一个问题,要求如何单独更改这些图。我想知道如何在机器B的图上使用alpha = 0.5,但不是其他的。 – blehman

+1

原理相同:'... + scale_alpha_manual(values = c(1,0.5,1))' –

+0

使用... + scale_alpha_manual(values = c(1,0.5,1))不幸的是不会更改任何alpha在这个例子中的值。 – blehman