R 如何根据分组条形图中特定变量的降序重新排序

R 如何根据分组条形图中特定变量的降序重新排序,r,ggplot2,R,Ggplot2,我试图根据其中一个变量对图形条进行重新排序,在本例中,y变量是按降序排列的,而不是按字母x排列的 x<-c("Jan","Feb","Mar") y <- c(2000, 23400, 26800) z<-c(1100,5000,6000) df<-data.frame(x,y,z) View(df) library(reshape2) library(ggplot2) df.long<-melt(df

我试图根据其中一个变量对图形条进行重新排序,在本例中,y变量是按降序排列的,而不是按字母x排列的

x<-c("Jan","Feb","Mar")
y <- c(2000, 23400, 26800)
z<-c(1100,5000,6000)
df<-data.frame(x,y,z)
View(df)

library(reshape2)
library(ggplot2)

df.long<-melt(df)
ggplot(df.long,aes(x=x, y=value,fill=variable))+geom_col(position = "dodge", width=0.9)

x试试这个。您可以使用
reorder()
函数根据重塑后的值在
x
中排列数据。代码如下:

library(reshape2)
library(ggplot2)

#Data
df.long<-melt(df)
#Plot
ggplot(df.long,aes(x=reorder(x,-value),
                   y=value,fill=variable))+
  geom_col(position = "dodge", width=0.9)+
  xlab('Month')+
  theme(legend.position = 'bottom')
library(重塑2)
图书馆(GG2)
#资料
df.long