R中的列着色

时间:2016-06-10 15:33:00

标签: r

我有以下代码在R中生成barchart

library(lattice)
options(scipen = 10)

barchart(Cost~KPI, data=lowD, groups = Sequence, 
         scales=list(x=list(rot=90,cex=0.8)),
         xlab="Performance Indicators", ylab="Timetable Cost (£)",
         ylim = c(0,50000),
         col=c("aquamarine","coral"))

从附件中可以看出,每列进一步分为3个部分。有谁知道这3件代表什么?我虽然他们表示每个乘客类型的金额,但似乎我错了。理想情况下,我想将每一栏分成3个部分,以表明每种乘客的贡献,为每件作品涂上不同的颜色并添加一个图例。

我正在使用的输入如下:

**PassengerType**   **Cost**        **KPI**        **CurrOpt**
  Business              0          Crowdedness       Current
  Commute               0          Crowdedness       Current
  Leisure               0          Crowdedness       Current
  Business            41349        Journey Time      Current
  Commute             18247        Journey Time      Current
  Leisure              5050        Journey Time      Current
  Business            36654        Punctuality       Current
  Commute             16418        Punctuality       Current
  Leisure              4470        Punctuality       Current
  Business            10496        Waiting Time      Current
  Commute              4800        Waiting Time      Current
  Leisure              1280        Waiting Time      Current
  Business               0         Crowdedness       Optimal
  Commute                0         Crowdedness       Optimal
  Leisure                0         Crowdedness       Optimal
  Business             42642       Journey Time      Optimal
  Commute              18839       Journey Time      Optimal
  Leisure               5208       Journey Time      Optimal
  Business             25319       Punctuality       Optimal
  Commute              11258       Punctuality       Optimal
  Leisure               3087       Punctuality       Optimal
  Business              9731       Waiting Time      Optimal
  Commute               4536       Waiting Time      Optimal
  Leisure               1184       Waiting Time      Optimal

Bar Plot

1 个答案:

答案 0 :(得分:1)

由于您没有添加数据框,因此并不完全清楚您想要什么。

但是,在栏内为不同的序列或值着色的选项之一是:

# Create data
vector <- seq(1:4)
mat.1    <- matrix(sample(vector, 40, replace = T), nrow=4, byrow = T)
mat.2   <-  matrix(rep(1,40), nrow=4, byrow=T)

# Define conditions and colors under the condition. So you might use something like that: 
cols <- ifelse((mat.1 ==1) , "blue",
ifelse( (mat.1 ==2), "yellow",
ifelse( (mat.1 ==3) , "skyblue",
ifelse((mat.1 ==4), "red", "purple" ))))

barplot(mat.2,col=cols, width = c(0.2),xlim = c(0,4),beside=F)

输出(这里的点是基于值的条形图中的不同颜色) enter image description here