R - ggplot通过acsending - factor排序x轴

时间:2018-04-10 19:21:09

标签: r ggplot2

我正在使用ggplot制作条形图。代码如下:

ggplot(foo, aes(thisCol1IsAFactor, Col2, fill = Col3)) + 
  geom_bar(stat="identity", position   = "dodge") + 
  scale_fill_brewer(palette = "Set1")

我想按升序排序 thisCol1IsAFactor ;让它沿x轴增加。 thisCol1IsAFactor列的顺序如下:

7/31/2017
7/31/2017
7/31/2017
7/31/2017
8/7/2017
8/7/2017
8/7/2017
8/7/2017

每个观察都有自己的日期,因此有重复的日期。条形图工作并且看起来很棒,除了排序/排序使它有点难以阅读。日期不会按x轴的时间顺序显示。

2 个答案:

答案 0 :(得分:0)

你必须添加这个功能:

scale_x_discrete(thisCol1IsAFactor)

ggplot(foo, aes(thisCol1IsAFactor, Col2, fill = Col3)) + 
  geom_bar(stat="identity", position   = "dodge") + 
scale_x_discrete(thisCol1IsAFactor) +
  scale_fill_brewer(palette = "Set1")

答案 1 :(得分:0)

因子按字母顺序自动排序(将数字视为字符串) - 这就是排序不佳的原因。您需要将它们视为日期。尝试

library(tidyverse)

foo %>%
mutate(
  Col1AsDate = as.Date(thisCol1IsAFactor, "%m/%d/%Y")
) %>%
ggplot(aes(Col1AsDate, Col2, fill = Col3)) + 
  geom_bar(stat="identity", position   = "dodge") + 
  scale_fill_brewer(palette = "Set1")

您也可以手动重新排序所有因素,但这要容易得多。