首页 文章

R条形图中的条形图的不同颜色

提问于
浏览
1

如何为R中的条形图的特定条形图设置不同的颜色?特定的条形集动态变化 .

enter image description here

背后的逻辑是,我必须找出数据的最后3个月并为这些条形图应用不同的颜色,除此之外,我必须将相同的颜色应用于前几年的那些月份 .

可以说,现在是2017年5月,所以最后3个月是2月,3月,4月 . 因此,我必须在图表中每年仅对这些月份应用不同的颜色 .

我试图通过r在这里使用plotly或highcharts .

1 回答

  • 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

相关问题