【问题标题】:How to reorder the x axis on a stacked area plot如何在堆积面积图上重新排序 x 轴
【发布时间】:2016-04-29 19:14:24
【问题描述】:

我有以下数据框并想绘制堆积面积图:

library(ggplot2)
set.seed(11)
df <- data.frame(a = rlnorm(30), b = as.factor(1:10), c = rep(LETTERS[1:3], each = 10))

ggplot(df, aes(x = as.numeric(b), y = a, fill = c)) + 
    geom_area(position = 'stack') +
    theme_grey() +
    scale_x_discrete(labels = levels(as.factor(df$b))) +
    theme(axis.text.x = element_text(angle = 90, hjust = 1))

我系统上的结果图如下所示:

不幸的是,x 轴似乎没有出现。我想绘制旋转的df$b 的值,使它们不重叠,最终我想以特定的方式对它们进行排序(还没有那么远,但我会接受任何建议)。

另外,根据?factor() 使用带有因子的as.numeric() 并不是最好的方法。当我打电话给ggplot,但把as.numeric() 换成aes(x=... 时,情节就空了。

有没有更好的方法来做到这一点?

【问题讨论】:

  • 试试这个似乎可行:scale_x_continuous(limits = c(0, max(as.numeric(df$b))), breaks = seq(0, max(as.numeric(df$b)), 1))
  • 谢谢!这似乎有效!

标签: r plot ggplot2 stacked-area-chart


【解决方案1】:

b 作为一个因素。您还需要添加与fill 相同的group 美学。 (这告诉ggplot 如何在不同的因子水平之间“连接点”。)

ggplot(df, aes(x = b, y = a, fill = c, group = c)) + 
    geom_area(position = 'stack') +
    theme(axis.text.x = element_text(angle = 90, hjust = 1))

至于顺序,x轴将按照因子水平的顺序排列。要更改轴的顺序,只需更改因子水平的顺序。如果您基于数字列(或数字列的函数),reorder() 效果很好。对于任意顺序,只需在 factor 调用中直接指定级别的顺序,例如:df$b = factor(df$b, levels = c("1", "5", "2", ...) 更多示例,请参阅 r-faq Order bars in ggplot。你的不是条形图,但原理是一样的。

【讨论】:

  • 谢谢,这帮助很大!我错过了group=c 部分。
猜你喜欢
  • 2014-02-07
  • 2014-07-07
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多