r - 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
对于我正在尝试使用的解决方案,是否有更好的解决方案?如果没有,那么我该如何解决这个错误?我已经在网上查看了一些解决方案,但似乎没有一个对我有用。
解决方案
我认为这应该可以解决问题。您不需要将 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 创建
推荐阅读
- c# - iOS 13:Flurry Unity SDK 启动时应用程序崩溃
- azure-functions - 在逻辑应用中将多个相同结构的 XML 文件合并为单个 xml
- arrays - 获取数组AngularJS中的最后一项
- javascript - 使用多个下拉列表更新总成本
- php - Laravel 在重定向路由上填充数据
- android - 如何在 Android Studio 的 com.XX 下添加活动?
- windows - 如何在批处理文件中获取今天日期的当前日期
- r - 如何使用 cor() 函数计算两个变量与第三个变量的组合相关性?
- angular - 如何对私有函数内的按钮的单击事件进行单元测试?
- single-sign-on - 使用 KNOX 的 NiFi SSO:请求证书时出错