重新排序 Columns/Legend
Reorder Columns/Legend
Country_Of_Data Year Appr_Country Apprehension
## <chr> <chr> <chr> <dbl>
## 1 Afghanistan 2010 PAN 17
## 2 Afghanistan 2011 PAN 0
## 3 Afghanistan 2010 MEX 3
## 4 Afghanistan 2011 MEX 4
## 5 Afghanistan 2010 US 0
## 6 Afghanistan 2011 US 19
ggplot(Afghan_Appr, aes(Year, Apprehension, fill = Appr_Country)) + geom_bar(stat = "identity", position = 'dodge')
我输出的图基本上每年绘制三个柱状图,但当我希望它是 PAN、MEX、US 时,它会按 MEX、PAN、US 的顺序绘制。有没有办法切换顺序?我尝试使用 Afghan$Appr_Country 来切换顺序,但由于数据的结构,它不起作用。
使用 forcats
包中的 fct_relevel
来切换 df
的顺序
library(ggplot2)
library(forcats)
ggplot(Afghan_Appr, aes(x = Year, y = Apprehension, fill = fct_relevel(Appr_Country, c("PAN", "MEX", "US")))) +
geom_bar(stat = "identity", position = "dodge")
这个有用吗?
Afghan_Appr[,3] = factor(Afghan_Appr[,3], level= c('PAN','MEX','US'))
ggplot(Afghan_Appr, aes(Year, Apprehension, fill = Appr_Country)) + geom_bar(stat = "identity", position = 'dodge')
Country_Of_Data Year Appr_Country Apprehension
## <chr> <chr> <chr> <dbl>
## 1 Afghanistan 2010 PAN 17
## 2 Afghanistan 2011 PAN 0
## 3 Afghanistan 2010 MEX 3
## 4 Afghanistan 2011 MEX 4
## 5 Afghanistan 2010 US 0
## 6 Afghanistan 2011 US 19
ggplot(Afghan_Appr, aes(Year, Apprehension, fill = Appr_Country)) + geom_bar(stat = "identity", position = 'dodge')
使用 forcats
包中的 fct_relevel
来切换 df
library(ggplot2)
library(forcats)
ggplot(Afghan_Appr, aes(x = Year, y = Apprehension, fill = fct_relevel(Appr_Country, c("PAN", "MEX", "US")))) +
geom_bar(stat = "identity", position = "dodge")
这个有用吗?
Afghan_Appr[,3] = factor(Afghan_Appr[,3], level= c('PAN','MEX','US'))
ggplot(Afghan_Appr, aes(Year, Apprehension, fill = Appr_Country)) + geom_bar(stat = "identity", position = 'dodge')