2017-04-22 83 views
2

特定條我中的R設置顏色爲滿足的條件

SalesWeek   GS  IS   MM   MN  MN 
1   2  0.00 742340 3551557.4 384585.0 12044.64 
2   3  0.00  0 1770886.0 685880.0  0.00 
3   4  0.00  0 2720725.4 399797.9 391244.64 
4   5  0.00  0 12301207.0 663900.0 122696.43 
5   6  0.00  0 8973689.9 3031950.9 12044.64 
6   7  0.00  0 264528.3  0.0 314984.64 
7   8  0.00  0 11223543.6 1586324.0  0.00 
8   9  0.00  0 18721800.9  0.0  0.00 
9   10 309085.84  0 12494273.8 7893507.5  0.00 

數據幀(weekarea)以下數據幀具有其它列,如「NL」,「VS」,和「SL」。設置數據幀之後,我繪製他們在一個barplot

ggplot(weekarea, aes(x=SalesWeek, y=NL))+ 
    geom_bar(stat="identity")+ 
    scale_y_continuous(labels=scales::comma)+ 
    geom_vline(xintercept=12, color="red")+ 
    xlab("Weeks of the year")+ 
    ylab("Revenue in Pesos") 

我想顏色對應於周11和22之間條的條所以我修改以上這樣的第一行:

ggplot(weekarea, aes(x=SalesWeek, y=NL, fill=(SalesWeek>=12 && SalesWeek<22))) 

問題是它着色所有酒吧。有人可以幫助我正確設置它嗎?

回答

1

你可以試試下面的方法:

library(ggplot2) 

weekarea$pfill <- as.factor((weekarea$SalesWeek>=3 & weekarea$SalesWeek < 5)*1) ##Make a variable basis the conditional logic 

###Use the pfill variable in the aes asthetics in ggplot2 
ggplot(weekarea, aes(x=SalesWeek, y=MM,fill=pfill))+ 
    geom_bar(stat="identity")+ 
    scale_y_continuous(labels=scales::comma)+ 
    geom_vline(xintercept=12, color="red")+ 
    xlab("Weeks of the year")+ 
    ylab("Revenue in Pesos") 

在這裏我們可以看到的顏色是譯員更加和week4不同

enter image description here

+1

I試過它,但填充列都是0.我認爲這意味着一切都是錯誤的。 –

+0

@Angelo Louise Lopez創建填充時使用單個「&」不是「&&」 – PKumar

+1

@kpradeep OMG你是一個救星!我現在得到了我出錯的地方! –

1

一種簡單的方式就是一個額外的列添加到數據框指定條的顏色,例如在本例中:

library(ggplot2) 
weekarea<-read.table(text="SalesWeek   GS  IS   MM   MN  MN 
    2  0.00 742340 3551557.4 384585.0 12044.64 
    3  0.00  0 1770886.0 685880.0  0.00 
    4  0.00  0 2720725.4 399797.9 391244.64 
    5  0.00  0 12301207.0 663900.0 122696.43 
    6  0.00  0 8973689.9 3031950.9 12044.64 
    7  0.00  0 264528.3  0.0 314984.64 
    8  0.00  0 11223543.6 1586324.0  0.00 
    9  0.00  0 18721800.9  0.0  0.00 
    10 309085.84  0 12494273.8 7893507.5  0.00", header=TRUE) 

#add color specification: 
weekarea$color=ifelse(weekarea$SalesWeek>5 & weekarea$SalesWeek<10, "red", "blue") 

#add fill to aes 
ggplot(weekarea, aes(x=SalesWeek, y=MM, fill= color))+ 
    geom_bar(stat="identity")+ 
    scale_y_continuous(labels=scales::comma)+ 
    geom_vline(xintercept=12, color="red")+ 
    xlab("Weeks of the year")+ 
    ylab("Revenue in Pesos")