![](/img/trans.png)
[英]r ggplot2 modify x axis labels of stacked bar plot with interaction aes
[英]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.