【问题标题】:Change Background color of polar plot in ggplot according to a factor根据一个因素更改ggplot中极坐标图的背景颜色
【发布时间】:2017-11-01 22:39:15
【问题描述】:

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

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

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

Month&lt;- 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"))

【问题讨论】:

  • 您需要提供最少的数据和代码示例
  • 我添加了一个小子集和我的代码

标签: r ggplot2 polar-coordinates


【解决方案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"))

【讨论】:

  • 非常好。您可以根据原始数据动态设置高度,将y = 4替换为y = max(table(df))
猜你喜欢
  • 2020-10-25
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 2016-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
相关资源
最近更新 更多