【问题标题】:customise or use another column for facet_wrap labels为 facet_wrap 标签自定义或使用另一列
【发布时间】:2018-03-30 04:27:19
【问题描述】:

我已经能够在 facet_wrap 标签中部署缩写月份,但我想在适当的位置使用 J、F、M、A、M、J、J、A、S、O、N、D 类型的标签。我的代码如下。

   ggplot(sr3, aes(x=Month2, fill = Year)) +  geom_bar() + 
   theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
   facet_wrap(~Province) +
   labs(title ="US Drone Strikes in Afghanistan from Jan 2015- Mar 2018", 
   x = "Monthly distribution across Provinces", y = "No. of Strikes")

【问题讨论】:

  • 问题是当J表示一月、六月和七月或说M表示三月、五月时如何排序字母......我也可以颠倒年份的顺序。因为我希望最早的年份显示在底部。

标签: axis-labels facet-wrap


【解决方案1】:

试试这个,它应该与因子一起使用:

   ggplot(transform(sr3, Month2=factor(Month2, levels=c("J","F","M",......))),aes(x=Month2, fill = Year)) +  geom_bar() + 
   theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
   facet_wrap(~Province) +
   labs(title ="US Drone Strikes in Afghanistan from Jan 2015- Mar 2018", 
   x = "Monthly distribution across Provinces", y = "No. of Strikes")

【讨论】:

  • 我的恐惧成真了。它给出了三月和五月的错误如下。 Error in levels(*tmp*, value = if (nl == nL) as.character(labels) else paste0(labels, : factor level [5] is duplicated
  • 我尝试使用如下代码创建另一列:sr3$Month3 <- factor(substr(sr3$Month, 1,1), levels = c("J","F","M","A","M","J","J","A","S","O","N","D")) 但问题再次是重复级别错误。如何处理。
  • 可能保持水平不变并使用scale_x_discrete=(labels=c("J","F","M","N","M"......)更改标签?将是一种解决方法,但可能会解决它。
  • 感谢我的最终代码是ggplot(sr3, aes(x=Month, fill = Year)) + geom_bar() + scale_x_discrete(labels = c("J","F","M","A","M","J","J","A","S","O","N","D")) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + facet_wrap(~Province) + labs(title ="US Drone Strikes in Afghanistan from Jan 2015- Mar 2018", x = "Monthly distribution across Provinces", y = "No. of Strikes") 但是,最后一个问题是如何更改堆叠年份的顺序。
  • 最后一件事如何将年份的堆栈修改为倒序。这将完成我的任务。
猜你喜欢
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
  • 1970-01-01
  • 2019-11-27
  • 2014-12-26
  • 2017-02-10
相关资源
最近更新 更多