根据因子更改ggplot中极坐标图的背景颜色

时间:2017-11-01 22:39:16

标签: r ggplot2 polar-coordinates

我根据M.Baggott(http://rpubs.com/mattbagg/circular)提供的代码构建了一个极坐标图,以总结全年按周发生的事件数。有没有一种方法可以将条形图保持灰色并根据月份填充背景(即12个彩色饼图代表灰色频率条后面的月份)?感谢

Polar Plot Colour Polar Plot Grey

以下是一小部分数据和我的代码:

Week<- c(30, 21, 20, 26, 24, 22, 26, 26, 30, 25, 23, 23, 22, 24, 23, 22, 26, 20, 20, 23)

Month<- c("July", "May", "May","June", "June", "June", "June", "June", "July", "June", "June", "June", "June", "June", "June", "June", "July", "May", "May", "June")

df<- data.frame(Week=Week,Month=Month)

ggplot(df, aes(x = Week)) + 
       geom_histogram(breaks = seq(1, 52), colour = "white") + 
       coord_polar(start = 0) + 
       theme_minimal() + 
       scale_colour_gradient(colours=rainbow(12)) + 
       ylab("Count") + 
       ggtitle("Count by Week") + 
       scale_x_continuous("", limits = c(1, 52), breaks =c(1,5,9,13,18,22,26,31,35,39,44,48),labels=c("January","February","March","April","May","June","July","August","September","October","November", "December"))

1 个答案:

答案 0 :(得分:1)

这是一个想法:

使用geom_col定义带有单独data.frame的彩色背景和使用geom_bar的离散比例。

library(ggplot2)
ggplot(df, aes(x = Week)) + 
  geom_col(data = data.frame(seq = as.factor(seq(1, 52)),
                             month =  factor(rep(c("January","February","March","April","May","June","July","August","September","October","November", "December"), 
                                          times = diff(c(0,5,9,13,18,22,26,31,35,39,44,48,52))),
                                          levels = c("January","February","March","April","May","June","July","August","September","October","November", "December")),
                             y = 4),
           aes(x = seq, y = y, fill = month), width = 1)+
  geom_bar(colour = "white", stat = "count", show.legend = F) + 
  theme_minimal() + 
  ylab("Count") + 
  ggtitle("Count by Week") + 
  coord_polar(start = 0)+
  scale_x_discrete(breaks =c(1,5,9,13,18,22,26,31,35,39,44,48)+2,
                   labels=c("January","February","March","April",
                            "May","June","July","August","September",
                            "October","November", "December"))

enter image description here