r - 如何在 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 中的一个示例。
如果该图像令人困惑,我很抱歉。如果有任何其他显示数据的建议,请分享。
解决方案
推荐阅读
- python - Python 在井字游戏中定义函数
- excel - 如何编写适用于任何工作簿的排序代码?
- machine-learning - 如何在python中绘制正确的超平面
- editor - ThebeLab的输入框(使用codemirror)如何设置样式?
- java - Java 11 (Zulu) 中的 DateTimeFormatter 不适用于 AM / PM 格式
- php - 如何打印脸书评论
- java - 分而治之的递归矩阵乘法
- python-3.x - 当我尝试使用 Flask rest API 上传文件时,我得到:上游过早关闭连接,同时从上游读取响应标头,客户端
- python - 如何制作动态静态属性?
- node.js - 它发送了 4 倍的会员数量