繁体   English   中英

R:手动排序 X 轴数据时的堆积条形图错误 (ggplot2)

[英]R: Stacked Bar Plot Error When Manually Ordering X Axis Data (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

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

我认为这应该可以解决问题。 您不需要将 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 月 7 日创建在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM