【问题标题】:Boxplot with two values per year每年有两个值的箱线图
【发布时间】:2019-12-04 23:48:12
【问题描述】:

我有一个类似这个的数据框:

year LE  Rn
2005 400 500
2006 402 501
2007 403 502
2008 404 503
2009 405 504
2010 406 503

现在我想要一个箱形图,x 轴为年份,y 轴为水当量 (mm),然后 LE 和 Rn 每年相邻。

我试过了:

ggplot(df, aes(x=as.factor(df$year),y=df$LE, fill=df$Rn)) +
         geom_bar(stat="identity",fill="steelblue", position = position_dodge())

但它只绘制 LE 而不是 Rn。

谢谢!

【问题讨论】:

标签: r ggplot2 bar-chart


【解决方案1】:

您需要将数据重排为“长”格式。这意味着您想要躲避的变量必须出现在同一列中。另外,请注意我是如何引用 aes 中的值的。你也应该。

library(ggplot2)
library(tidyr)

xy <- read.table(text = "year LE  Rn
2005 400 500
2006 402 501
2007 403 502
2008 404 503
2009 405 504
2010 406 503", header = TRUE)

xy <- gather(xy, key = stats, value = value, -year)

# Notice how values are now in "long" format.
> head(xy)
  year stats value
1 2005    LE   400
2 2006    LE   402
3 2007    LE   403
4 2008    LE   404
5 2009    LE   405
6 2010    LE   406
> tail(xy)
   year stats value
7  2005    Rn   500
8  2006    Rn   501
9  2007    Rn   502
10 2008    Rn   503
11 2009    Rn   504
12 2010    Rn   503

ggplot(xy, aes(x = as.factor(year), y = value, fill = stats)) +
  theme_bw() +
  scale_fill_brewer(palette = "Set1") +
  geom_bar(stat = "identity", position = position_dodge())

【讨论】:

  • geom_bar(stat = 'identity, …)geom_col(…).
  • 谢谢!效果很好:)
  • @KonradRudolph 随时编辑我的帖子。 geom_col 确实是这些天孩子们做的很酷。
猜你喜欢
  • 2021-09-29
  • 1970-01-01
  • 2021-09-08
  • 2020-03-02
  • 2018-07-20
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
  • 2015-09-24
相关资源
最近更新 更多