2017-05-09 207 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

相关问题