根据R中的列值更改条形图中条形的颜色

时间:2018-03-17 12:26:08

标签: r

我有一个代码段,显示不同月份的数字和相应的季节。我想把它表示为R中的条形图,条形图的颜色与季节相对应。请帮忙。

month<-c(1:12)
season<-c('Winter','Spring','Spring','Summer','Summer','Summer','Rainy','Rainy','Rainy','Autumn','Autumn','Winter')
freq<-c(5,10,15,2,13,4,7,9,8,6,12,10)
df<-data.frame(month,season,freq)

df$color<-factor(df$season,labels = RColorBrewer::brewer.pal(length(unique(df$season)),name = 'Set1'))

barplot(df[,3],names.arg=df[,1],
    xlab='Month',ylab='Maximum Frequency',
    main='Months',
    col=df$color,col.main='Blue')

legend("topright", cex=0.6,ncol=2,text.width = 1.6,bty = 'n',
   x.intersp = .2,y.intersp = .59,box.lwd = 0,
   legend = unique(df[,2]),
   fill = df[,4])

将名称更改为其他调色板名称不会更改颜色。还有什么可以做的。请帮忙。

1 个答案:

答案 0 :(得分:0)

你搞砸了因素。这是正确的代码(代码中的解释):

month<-c(1:12)
season<-c('Winter','Spring','Spring','Summer','Summer',
          'Summer','Rainy','Rainy','Rainy','Autumn','Autumn','Winter')
freq<-c(5,10,15,2,13,4,7,9,8,6,12,10)
df<-data.frame(month,season,freq)

# here we gets the colors for unique seasons
palette <- RColorBrewer::brewer.pal(length(unique(df$season)),name = 'Set1')
# here we're mapping each season with a color, exploiting the fact 
# that factors are integers and we use them as indexes in the palette
# ("as.factors" is not really necessary here because season column is already factors) 
df$color <- palette[as.factor(df$season)]   

barplot(df[,3],names.arg=df[,1],
        xlab='Month',ylab='Maximum Frequency',
        main='Months',
        col=df$color,col.main='Blue')

# here we need to associate a fill color for each unique season; 
# we're doing this using "duplicated" function
legend("topright", cex=0.6,ncol=2,text.width = 1.6,bty = 'n',
       x.intersp = .2,y.intersp = .59,box.lwd = 0,
       legend = df$season[!duplicated(df$season)],
       fill = df$color[!duplicated(df$season)])

enter image description here