R工作室条形图

发布于 2025-01-16 17:04:29 字数 1032 浏览 1 评论 0原文

我有以下数据框:

structure(list(share.beer = c(0.277, 0.1376, 0.1194, 0.0769, 
0.0539, 0.0361, 0.0361, 0.0351, 0.0313, 0.03, 0.0119, 0.0084, 
0.007, 0.0069), country = c("Brazil", "China, mainland", "United States", 
"Thailand", "Vietnam", "China, mainland", "China, mainland", 
"China, mainland", "China, mainland", "Argentina", "Indonesia", 
"China, mainland", "China, mainland", "India"), Beer = c("soyb", 
"maiz", "soyb", "cass", "cass", "whea", "rape", "soyb", "rice", 
"soyb", "cass", "cott", "swpo", "rape")), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -14L))

我想创建一个条形图,以便啤酒类型出现在图例中,国家/地区作为 y 值,而 share.beer 是我要填充的值。

我尝试了各种方法,包括下面的代码,但我无法得到我想要的结果。例如,在这里,我保留了变量“啤酒””

df %>%
  pivot_longer(cols = -Country, values_to = "Count", names_to = "Type") %>%
  ggplot() +
  geom_col(aes(x = reorder(Country, -Count), y = Count, fill = Beer))

但是,我收到错误

无法将分享啤酒啤酒结合使用。

有什么帮助吗?

I have the following dataframe:

structure(list(share.beer = c(0.277, 0.1376, 0.1194, 0.0769, 
0.0539, 0.0361, 0.0361, 0.0351, 0.0313, 0.03, 0.0119, 0.0084, 
0.007, 0.0069), country = c("Brazil", "China, mainland", "United States", 
"Thailand", "Vietnam", "China, mainland", "China, mainland", 
"China, mainland", "China, mainland", "Argentina", "Indonesia", 
"China, mainland", "China, mainland", "India"), Beer = c("soyb", 
"maiz", "soyb", "cass", "cass", "whea", "rape", "soyb", "rice", 
"soyb", "cass", "cott", "swpo", "rape")), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -14L))

I want to create a barplot so that the beer type appears in the legend, the countries as y values while the share.beer are my values to be filled.

I have tried in various ways, including the following code, but I can't get the result I would like to. Here, for instance, I kept the variable "Beer""

df %>%
  pivot_longer(cols = -Country, values_to = "Count", names_to = "Type") %>%
  ggplot() +
  geom_col(aes(x = reorder(Country, -Count), y = Count, fill = Beer))

However, I get an error

Can't combine share beer and Beer .

Any help?

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

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

发布评论

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

评论(1

赠佳期 2025-01-23 17:04:29

实际上,您不需要 pivot_longer 来创建合适的数据框。您可以使用以下代码:

library(tidyverse)
df %>%
  ggplot() +
  geom_col(aes(x = reorder(country, -share.beer), y = share.beer, fill = Beer)) +
  xlab("Country") +
  ylab("Share beer") +
  coord_flip()

输出:

在此处输入图像描述

You actually don't need the pivot_longer to create a suitable dataframe. You can use the following code:

library(tidyverse)
df %>%
  ggplot() +
  geom_col(aes(x = reorder(country, -share.beer), y = share.beer, fill = Beer)) +
  xlab("Country") +
  ylab("Share beer") +
  coord_flip()

Output:

enter image description here

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