【问题标题】:ggplot2 barplot two data frames comparisonggplot2 barplot 两个数据框比较
【发布时间】:2016-08-06 20:04:55
【问题描述】:

我想在 R 中创建一个条形图并在两个不同的 data.frame 中比较相同的值

我的数据是这样的

第一个 DF:

      2004  2005  2006 unit region

   1  1500  1000  2000  X    region1
   2  1000  2500  2800  Y    region1
   3  2000  2050  1900  X    region2
   4  2200  2100  2000  Y    region2
etc.

第二个DF:

     2004  2005  2006 unit region

  1   5     10    12   PP   region1
  2   3     5     8    SS   region1
  3   8     12    11   PP   region2
  4   7     5     5    SS   region2
etc.

我想做的是一个视觉比较:

  1. 条形图(集群) - 区域 1 单元 X 与第二个 DF 单元 PP 的区域 1 相同。年(2004、2005、2006)
  2. 折线图数据同上
  3. 条形图(集群) - 一组 10 个区域,单元 Y 与第二个表单元 SS 的 10 个区域相同。年(2004、2005、2006) 我想要一个条形图(集群条形图)。

如果有人可以帮助我,我将不胜感激,尝试一整天都这样做,但无法继续前进。

谢谢!!!

【问题讨论】:

  • 您至少应该在reproducible format 中分享您的数据。还要展示您尝试过的内容,并具体询问您遇到困难的地方。这个问题读起来就像你现在给我们布置作业。您可能应该首先将您的数据放入更多 tidy format 以使其更易于与 ggplot 一起使用。

标签: r ggplot2 bar-chart linechart


【解决方案1】:
2004  2005  2006 unit region
1500  1000  2000  X    region1
1000  2500  2800  Y    region1
2000  2050  1900  X    region2
2200  2100  2000  Y    region2

df1 <- read.table(con <- file("clipboard"), header = T)

2004  2005  2006 unit region
5     10    12   PP   region1
3     5     8    SS   region1
8     12    11   PP   region2
7     5     5    SS   region2

df2 <- read.table(con <- file("clipboard"), header = T)

# Barplot (clustered) - region1 unit X with the same region1 from second DF unit PP. Years (2004, 2005, 2006)
df1$df <- 1
df2$df <- 2

require(reshape2)
require(ggplot2)

df <- rbind(df1, df2)
df <- melt(df, id.vars=c("region", "unit", "df"))

ggplot(df[(df$region=="region1" & df$df == 1) | (df$region == "region1" & df$unit == "PP"),], 
       aes(variable, value)) + 
  geom_bar(aes(fill = factor(df)), position = "dodge", stat="identity")


# Line chart the same data as above 
ggplot(df[(df$region=="region1" & df$df == 1) | (df$region == "region1" & df$unit == "PP"),], 
       aes(variable, value)) + 
  geom_line(aes(fill = factor(df)), stat="identity")

# Barplot (clustered) - a set of 10 regions with unit Y with the same 10 regions from second table unit SS. Years (2004, 2005, 2006) I would like to have a barplot (clustered barplot).
cat("For this one you'd need to provide a suitable example, as the current example has only 2 regions")

【讨论】:

  • 谢谢!非常适合我!不知道我必须转换 df,现在更有意义了!
猜你喜欢
  • 2021-11-20
  • 2020-06-02
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多