0

我正在尝试将每个站点的塑料计数的“观察到的”和“预期的”条配对,但无法弄清楚如何在我的 geom_col 图中包含我的“预期”列。我的报告将于 30 日到期(哎呀!)

我想要类似的东西(见下文)但不使用 Excel(我在 R 中花了 2 天时间试图破解它并决心成功!)

在此处输入图像描述

我的数据框如下:

df <- data.frame(
  Site_name = c("Albermarle", "Cabo Douglas", "Punta Puntas", 
                "Floreana Black Beach", "Punta Cormoran", "Loberia"),       Plastic_pieces = c(44, 215, 29, 31, 42, 260),
  Expected = rep(c(103.5), times = 6))

到目前为止,我的 geom_col 代码是:

ggplot(df, aes(x=Site.Name, y=Plastic_pieces, fill = Site.Name ))+
  geom_col()+
  theme_classic()+
  labs(y="Number of macroplastic pieces", x="Site Name")+
  theme(axis.line.x = element_line(size = 0.3, colour = "black"),
        axis.line.y = element_line(size = 0.3, colour = "black"),
        axis.line = element_line(size=1, colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        text=element_text(size = 12),
        axis.text.x=element_text(colour="black", size = 8),
        axis.text.y=element_text(colour="black", size = 12),
        axis.text.x.bottom = element_blank(),
        axis.title.x = element_blank(),
        axis.ticks.x.bottom = element_blank())+
        scale_fill_discrete(name="Site Name")+
  geom_text(aes(label=Plastic_pieces), position=position_dodge(width=0.9), vjust=-0.25)

在此处输入图像描述

我在网上看到了一些看起来可以提供帮助的代码,但我得到的结果与上面几乎相同,只是条形图是按降序排列的:

df %>%
  group_by(Plastic_pieces, Expected) %>%
  summarise(n=sum(Plastic_pieces, na.rm = TRUE)) %>%
  arrange(desc(Plastic_pieces)) %>%
  ggplot(aes(x=df$Site.Name, y=Plastic_pieces, fill = df$Site.Name)) +
  geom_col(position='dodge')

在此处输入图像描述

如果有人可以提供帮助,我将不胜感激!

干杯!

4

2 回答 2

0

这类问题的解决方案是多次将数据从宽格式重塑为长格式。我将使用包dplyrtidyr.

library(dplyr)
library(tidyr)
library(ggplot2)

df %>%
  pivot_longer(
    cols = -1,
    names_to = 'Group',
    values_to = 'Value'
  ) %>%
  ggplot(aes(Site_name, Value, fill = Group)) +
  geom_col(position = position_dodge()) +
  geom_text(aes(label = Value), position = position_dodge(width = 0.9), vjust = -0.25) +
  labs(y="Number of macroplastic pieces", x="Site Name") +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 60,hjust = 1))

在此处输入图像描述

于 2020-06-18T10:46:40.393 回答
0

这是一个简单而简短的解决方案。您需要做的就是用于melt()转换您的数据并position = position_dodge()在您的通话中geom_col()调用。

请参阅此处我用来绘制示例数据的代码。

df <- data.frame(
  Site_name = c("Albermarle", "Cabo Douglas", "Punta Puntas", 
                "Floreana Black Beach", "Punta Cormoran", "Loberia"),       Plastic_pieces = c(44, 215, 29, 31, 42, 260),
  Expected = rep(c(103.5), times = 6))

library(reshape2)
df_melt = melt(df, id.vars = "Site_name")

ggplot(df_melt, aes(x = Site_name, y = value, fill = variable)) + 
  geom_col(position = position_dodge())
于 2020-06-18T10:50:49.450 回答