2017-05-09 439 views
1

如何在R中爲條形圖的特定條形設置不同的顏色?一組特定的小節動態變化。R在條形圖中設置不同顏色的條形圖

enter image description here

的背後是,我必須找出過去3個月的數據,併爲那些酒吧應用不同的顏色,除此之外的邏輯,我有相同的顏色適用於那些個月昔年。假設現在是2017年5月,所以最近3個月是2月,3月,4月。所以我必須在圖表中每年僅對這些月份應用不同的顏色。

我試圖通過r在這裏使用plotly或highcharts。

回答

0

正如我所看到的,您所遇到的問題是顏色矢量的創建,而不是繪圖包的選擇。我經歷了兩種不同的方法。第一種是更手動的,第二種是更自動化的,但假定您在本月份要運行代碼,以便突出顯示報告的前3個月。但是,兩者都應該說明您可以自定義自己使用的方式。

library(lubridate) 
set.seed(12345) 
data <- data.frame(date=c(rep(c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),2),c("Jan","Feb","Mar","Apr")), 
        plotdata=(abs(rep(rnorm(28)*100)))) 
###this is manual and requires customization based on your data set ###  
mycol <- rep(4,nrow(data)) ## setting color vector to blue by default (value = 4) 
mycol[c(length(mycol),length(mycol)-1,length(mycol)-2, 
     length(mycol)-12,length(mycol)-13,length(mycol)-14, 
     length(mycol)-24,length(mycol)-25,length(mycol)-26)] <- 2 
barplot(data$plotdata,col=mycol) 

###Second Way: Define past 3 months from current month. Lubridate allows 
### for easy date calculations as shown below. 

past3months <- c(as.Date(Sys.Date()-months(1),"month"),as.Date(Sys.Date()-months(2),"month"),as.Date(Sys.Date()-months(3),"month")) 
past3months <- format(past3months,"%b") ### changing the date format to match the data #### 
data$mycol2 <- ifelse(data$date %in% past3months,2,4) 

barplot(data$plotdata,col=data$mycol2) 

的代碼將生成下面的圖兩個片(帶底座圖形制造) enter image description here

相關問題