Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中的ggplot2中绘制条形图中的多个变量(即类别)_R_Ggplot2_Geom Bar - Fatal编程技术网

如何在R中的ggplot2中绘制条形图中的多个变量(即类别)

如何在R中的ggplot2中绘制条形图中的多个变量(即类别),r,ggplot2,geom-bar,R,Ggplot2,Geom Bar,我试图为特定的数据集绘制条形图。我面临的问题是我无法理解如何在条形图中使用多个变量。我使用的数据集就是这种结构 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 =

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

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)
)
但我想在要显示的图形中也使用产品名称。数据集的结构就是这样的

键->产品名称->产品描述及其相应的成本

这是Excel中的一个示例

我很抱歉,如果那张图片让人困惑。
如果有任何其他显示数据的建议,请分享

您可以使用facet和一些选项从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()
结果:


您是否希望类似于excel中的绘图,或类似于以下内容的绘图:源数据%>%gatherkey2,val,以产品%>%ggplot,aeskey,Cost,fill=val+geom\u barstat=identity,position=position\u dodge+facet\u wrap~key2您的x轴打断似乎与实际数据无关,因此您没有标签。这是故意的吗?可能是相关的/复制的谢谢:这太棒了!!!实际上,我正在尝试将错误条添加到这些图形中。我可以添加条。但是他们没有被安置在我想要的地方。也就是说,每个错误条都没有放在相应的条上。相反,它们是不匹配的。在这方面你能给我建议/建议吗?最好问一个新问题。
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()