我有一个代码片段,显示不同的月份数字和相应的季节。我想将其表示为 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])
将名称更改为其他调色板名称不会更改颜色。还能做什么呢。请帮忙。
最佳答案
你搞乱了因素。这是正确的代码(代码中的解释):
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)])
关于r - 根据 R 中的列值更改条形图中条形的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49335989/