在R中创建分组条形图

问题描述 投票:0回答:1

我对R非常陌生,因此简化了说明会非常有帮助。

一段时间以来,我一直在努力在R中创建分组条形图。我希望在x轴上有几个月的时间。我希望条形图也按两个变量进行分组。这是我到目前为止尝试过的代码:

library(reshape2)
library(ggplot2)
Months2 <- c('January','February','March','April','May','June','July','August','September','October','November','December')
Qantas <- c(18775,16560,21093,16101,15948,18864,17252,16770,21082,16692,15795,21782)
Ideal <- c(16591,21570,20579,16048,14372,15269,18266,17488,16284,17794,18880,23600)

# reshaping into longdata
InboundQantaslong <- melt(InboundQantas, id=c("Month"))

# make the plot
ggplot(InboundQantaslong) +
  geom_bar(aes(x = Months2, y = value, fill = variable), 
           stat="identity", position = "dodge", width = 0.7) +
  scale_fill_manual("Number\n", values = c("red","blue"), 
                    labels = c(" Ideal", " Qantas")) +
  labs(x="\nMonth",y="Number\n") +
  theme_bw(base_size = 14)

这将返回错误“手动刻度中的值不足。需要15个,但仅提供2个。”如何解决此问题?

r rstudio bar-chart
1个回答
0
投票

您可以像这样更正您的代码

library(reshape2)
library(ggplot2)

InboundQantas <- cbind.data.frame(Months2,Qantas,Ideal)

# reshaping into longdata
InboundQantaslong <- melt(InboundQantas, id=c("Months2"))
ggplot(InboundQantaslong, aes(x = Months2, y = value, fill = variable)) +
  geom_bar(stat="identity", position = "dodge", width = 0.7) +
  scale_fill_manual("Number\n", values = c("red","blue"), 
                    labels = c(" Ideal", " Qantas")) +
  labs(x="\nMonth",y="Number\n") +
  theme_bw(base_size = 14)

或使用tidyverse,其中melt替换为pivot_longer,例如

InboundQantas %>% pivot_longer(-Months2, names_to = "variable", values_to = "value") %>% 
  ggplot(aes(x = Months2, y = value, fill = variable)) +
  geom_bar(stat="identity", position = "dodge", width = 0.7) +
  scale_fill_manual("Number\n", values = c("red","blue"), 
                    labels = c(" Ideal", " Qantas")) +
  labs(x="\nMonth",y="Number\n") +
  theme_bw(base_size = 14)
© www.soinside.com 2019 - 2024. All rights reserved.