首页 > 解决方案 > R:手动排序 X 轴数据时的堆积条形图错误 (ggplot2)

问题描述

嗨,提前感谢您的时间。

我从表格的 Excel 电子表格中导入了一些数据

    # A tibble: 3 x 5
  Question          `Very Unlikely` Unlikely Likely `Very Likely`
  <chr>                       <dbl>    <dbl>  <dbl>         <dbl>
1 when you graduate              20       57     36             7
2 in 10 years                     0       12     68            40
3 in 20 years                     0        2     32            86

我希望使用 ggplot 创建一个堆积条形图,其中 x 轴包含变量“问题”和每个后续列的一组四个堆积条(即“非常不可能”、“不太可能”)。y 轴应绘制每个相应问答对的编号值。我已成功创建此图,但 x 轴上的条形顺序似乎是随机的 - 它是“10 年后”、“20 年后”、“毕业后”

我希望按以下方式对每个问题对应的条形集进行排序:“毕业后”、“10 年后”、“20 年后”

我尝试了以下代码:

Fig3_Subset <- melt(Fig3[,c('Question','Very Unlikely','Unlikely','Likely','Very Likely')],id.vars = 1)

Fig3 %>% 
  dplyr::mutate(Question = factor(Question, 
                                    levels = c('in 10 years', 'when you graduate', 'in 20 years'))) %>%

ggplot(Fig3_Subset, mapping = aes(x = Question, y = value)) +
  geom_bar(aes(fill = variable), stat = "identity", position = "dodge") +
  ggtitle("How likely is it that you will be using AI in your work...") +
  theme(axis.title.x=element_blank()) + 
  labs(title = "How likely is it that you will be using AI in your work...", 
       y = "Count",
       fill = "Answer")

但它返回此错误:

Error: Aesthetics must be either length 1 or the same as the data (3): fill and y

对于我正在尝试使用的解决方案,是否有更好的解决方案?如果没有,那么我该如何解决这个错误?我已经在网上查看了一些解决方案,但似乎没有一个对我有用。

标签: rggplot2bar-chart

解决方案


我认为这应该可以解决问题。您不需要将 Question 列更改为因子,但您可以使用 forcats 中的 fct_inorder 函数来获得所需的顺序!它会自动识别字符列并将其转换为因子。“inorder”根据它们出现的顺序设置因子水平。您还可以 fct_reorder 按不同列中的值对因子水平进行重新排序。

library(tidyverse)
library(reshape2)

Fig3 <- tibble(Question = c("when you graduate", "in 10 years", "in 20 years"),
               `Very Unlikely` = c(20, 0, 0),
               Unlikely = c(57, 12, 2),
               Likely = c(36, 68, 32),
               `Very Likely` = c(7, 40, 86))

Fig3_Subset <- melt(Fig3[,c('Question','Very Unlikely','Unlikely','Likely','Very Likely')],id.vars = 1)

Fig3_Subset %>% 
  ggplot(Fig3_Subset, mapping = aes(x = fct_inorder(Question), y = value)) +
  geom_bar(aes(fill = variable), stat = "identity") +
  ggtitle("How likely is it that you will be using AI in your work...") +
  theme(axis.title.x=element_blank()) + 
  labs(title = "How likely is it that you will be using AI in your work...", 
       y = "Count",
       fill = "Answer")

reprex 包(v0.3.0)于 2020-11-07 创建 在此处输入图像描述


推荐阅读