首页 文章

在ggplot2中排序分组条时出错

提问于
浏览
1

我的数据采用长格式(按照分组条形图的要求),因此不同类别的值在一列中 . 数据是here .

现在,带有ggplot2的标准条形图按字母顺序排列条形图(在我的国家名称中,从阿根廷到乌干达) . 我想保持数据框中国家的顺序 . 使用建议here(即在 scale_x_discrete 函数中使用 limits= 选项),我得到以下图表:

enter image description here

我的代码是这样的:

mydata <- read_excel("WDR2016Fig215.xls", col_names = TRUE) 

y <- mydata$value
x <- mydata$country
z <- mydata$Skill

ggplot(data=mydata, aes(x=x, y=y, fill=z)) + 
            geom_bar(stat="identity", position=position_dodge(), colour="black") + 
            scale_x_discrete(limits=x)

图表很好地按照我的要求排序,但x轴由于某种原因被扩展 . 不知道是什么问题?

1 回答

  • 1

    这个?

    mydata$country <- factor(mydata$country, levels=unique(mydata$country)[1:30])
    ggplot(data=mydata, aes(x=country, y=value, fill=Skill)) + 
      geom_bar(stat="identity", position=position_dodge(), colour="black")
    

相关问题