首页 > 解决方案 > 如何在 R 中 ggplot2 的条形图中绘制多个变量(即类别)

问题描述

我正在尝试为特定数据集绘制条形图。我面临的问题是我无法理解如何在条形图中使用多个变量。我使用的数据集就是这种结构。

Source_Data <-
data.frame(
key = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
Product_Name = c(
  "Table",
  "Table",
  "Chair",
  "Table",
  "Bed",
  "Bed",
  "Sofa",
  "Chair",
  "Sofa"
),
Product_desc = c("XX", "XXXX", "YY", "X", "Z", "ZZZ", "A", "Y", "A"),
Cost = c(1, 2, 3, 4, 2, 3, 4, 5, 6)
)

我可以绘制条形图,其中成本在 Y 轴上,在 x 轴上键入 Product_desc 作为每个类别。我使用下面的代码来做到这一点。

ggplot(Source_Data, aes (key, Cost, fill = Product_desc)) + 
  geom_bar(stat = "identity", position = position_dodge()) + 
  scale_x_continuous(breaks = seq(2014, 2018, 2)) +
  scale_fill_brewer(palette = "Paired")

但我也想在要显示的图表中使用产品名称。数据集的结构就是这样的。

Key --> Product_Name --> Product_desc 及其对应的成本。

这是 Excel 中的一个示例。

在此处输入图像描述

如果该图像令人困惑,我很抱歉。如果有任何其他显示数据的建议,请分享。

标签: rggplot2geom-bar

解决方案


您可以使用构面和一些选项来实现类似于 Excel 中的示例。

Source_Data %>% 
  ggplot(aes(Product_Name, Cost)) + 
  geom_col(aes(fill = Product_desc), position = position_dodge(preserve = "single")) + 
  facet_wrap(~key, scales = "free_x", strip.position = "bottom") +
  theme(strip.placement = "outside") + 
  theme_bw()

结果:

在此处输入图像描述


推荐阅读