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

标签 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])

将名称更改为其他调色板名称不会更改颜色。还能做什么呢。请帮忙。

最佳答案

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

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

关于r - 根据 R 中的列值更改条形图中条形的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49335989/

相关文章:

r - 尺度变换和坐标系变换有什么区别

Rcpp - 如何计算 rowSums 恰好为 1 的矩阵

python - 如何从 Python 运行 R 脚本中包含的函数? R 函数的输入将来自 Python

json - 如何使用 jsonlite 包将数据从 json 格式导入 R

r - 使用网格时如何停止 R 绘图轴标签中的上标

r - 观星者输出几种型号R

基于R中字段的运行计数

r - 使用 gganimate 制作伯努利分布的动画并在 p = 0.5 处获得意外跳跃

r - svyglm 和加权 glm 之间的区别

在 R 脚本中运行可执行文件