Reputation: 41
I have the following data frame in 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
The data frame(weekarea) has other columns like "NL", "VS", and "SL". After setting up the data frame, I plotted them in a 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")
I wanted to color the bars corresponding to bars between weeks 11 and 22 so I figured to revise the first line above like this:
ggplot(weekarea, aes(x=SalesWeek, y=NL, fill=(SalesWeek>=12 && SalesWeek<22)))
Problem is it colored all bars. Can someone help me to set it up properly?
Upvotes: 2
Views: 71
Reputation: 24079
An easy way is just to add an extra column to the data frame specifying the color of the bars such as in this example:
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")
Upvotes: 1
Reputation: 11128
You can try the below approach:
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")
Here we can see the color is different for week3 and week4
Upvotes: 3