GGPLOT2:两个离散变量列的堆叠条图

发布于 2025-02-13 18:06:14 字数 858 浏览 0 评论 0 原文

我有一个带有三列的数据集(一个分类列和两差变量列)。我想制作一个堆叠的条图,以比较每个类别的两个离散变量的值。但是,我会获得连续的着色,而不是离散的颜色。

可重复的代码

sampleData <-  data.frame(grp = c("A","B", "C"),
                          var_1 = c(15,20, 25),
                          var_2 = c(12, 13, 20))
sampleData

p <- ggplot(sampleData, aes(x = grp, y = var_1, fill= var_2)) +
  geom_bar( stat="identity", position = "fill")+
  coord_flip()+ theme_bw()
p

相反,我想要的是

* var2 始终小于其相应的 var1 值特定的类别

感谢您的帮助!

I have a dataset with three columns (one categorical column and two-discrete variables column). I want to make a stacked bar plot to compare the values of the two discrete variables for each category. However, I get continuous coloring rather than discrete colors.

Reproducible code

sampleData <-  data.frame(grp = c("A","B", "C"),
                          var_1 = c(15,20, 25),
                          var_2 = c(12, 13, 20))
sampleData

p <- ggplot(sampleData, aes(x = grp, y = var_1, fill= var_2)) +
  geom_bar( stat="identity", position = "fill")+
  coord_flip()+ theme_bw()
p

Output from above code

Instead, what I want is

Expected output

*Var2 will always be smaller than its corresponding Var1 value for a particular category.

Thanks for the help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半岛未凉 2025-02-20 18:06:14

您的问题是,您没有将尖头固定在较长的范围内。

FixedData <- sampleData %>%
  pivot_longer(cols = c("var_1", "var_2"), names_prefix = "var_", 
               names_to = "Variable Number", values_to = "ValueName")

一旦这样做,问题就变得更容易解决。您只需要更改几件事,最著名的是 y fill 位置变量以使其正常工作。

p2 <- ggplot(FixedData, aes(x = grp, y = ValueName, fill = `Variable Number`)) +
  geom_bar(stat="identity", position = "stack")+
  coord_flip()+ theme_bw()

p2

Your problem here is that you haven't fixed your tibble from Wide to Long.

FixedData <- sampleData %>%
  pivot_longer(cols = c("var_1", "var_2"), names_prefix = "var_", 
               names_to = "Variable Number", values_to = "ValueName")

Once you do this, the problem becomes much easier to solve. You only need to change a few things, most notably the y, fill, and position variables to make it work.

p2 <- ggplot(FixedData, aes(x = grp, y = ValueName, fill = `Variable Number`)) +
  geom_bar(stat="identity", position = "stack")+
  coord_flip()+ theme_bw()

p2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文