R lattice bar chart: specify colour of legend?

风流意气都作罢 提交于 2019-12-07 13:51:22

问题


My data looks like this:

service,rating_1,rating_2,rating_3,rating_4,rating_5
renew_patent,0,0,1,2,11
apply_benefit,21,20,121,828,1744
apply_employment_tribunal,0,0,0,0,0

I want R to print me a histogram for each row, with the columns as the bars of the histogram.

I've got this so far:

require(lattice)
data <- read.csv("test.csv", header = TRUE)
colors = c('red', 'orange', 'yellow', 'blue', 'green')
barchart(rating_1+rating_2+rating_3+rating_4+rating_5 ~ service, data=data, 
  auto.key=list(space='right'), scales=list(x=list(rot=45)), 
  ylab="Percentage of total", col=colors)

It's working, but it's only changing the colour of the bars, not the colour of the legend.

How can I specify the colour of the legend as well as the bars?


回答1:


Rather than passing a col= parameter to barchart, lattice much prefers if you change the par.settings. In this case. the color of the bars is determined by superpose.polygon because you have different groups of ratings. This should do what you want

data<-data.frame(
    service = c("renew_patent", "apply_benefit", "apply_employment_tribunal"),
    rating_1 = c(0, 21, 0), 
    rating_2 = c(0, 20, 0),
    rating_3 = c(1, 121, 0), 
    rating_4 = c(2, 828, 0),
    rating_5 = c(11, 1744, 0)
)

colors = c('red', 'orange', 'yellow', 'blue', 'green')
barchart(rating_1+rating_2+rating_3+rating_4+rating_5 ~ service, data=data, 
  auto.key=list(space='right'), scales=list(x=list(rot=45)), 
  ylab="Percentage of total", par.settings=list(superpose.polygon=list(col=colors)))


来源:https://stackoverflow.com/questions/23528122/r-lattice-bar-chart-specify-colour-of-legend

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!