ggplot以特定顺序绘制x轴 [英] ggplot plot x axis in a specific order

查看:1275
本文介绍了ggplot以特定顺序绘制x轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我绘制的示例数据:
$ b
$ b

 年份名称数量
1 1998 allmylife - kcijojo 83
2 1997 doowopthathatthing - laurynhill 196
3 1998 gettinjiggywitit - willsmith 231
4 2000 idontwanttomissathing - aerosmith 82
5 1998 imyourangel - rkelly 121
6 2013 myall - mariahcarey 70

这是我的代码:

  library(ggplot2)
setwd(C:/ Users / Andrew / Desktop / music lyrics)
data = read.csv(summary.csv,header = FALSE,stringsAsFactors = FALSE)
names(data)= c('year','names ','count')

ggplot(data,aes(names,count,fill = year))+
geom_bar(stat ='identity')+
theme .text.x = element_text(angle = 90,hjust = 1))

PL ot:

如何对x轴进行排序,使其从1998年,1999年,2000年...年开始? (而不是随机绘制它们)

解决方案

这将按年排序,然后按字母顺序排列。 p>

  d < -  read.csv(text =year,names,count 
1998,allmylife - kcijojo,83
1997,doowopthatthing - laurynhill,196
1998,gettinjiggywitit - willsmith,231
2000,idontwanttomissathing - aerosmith,82
1998,imyourangel - rkelly,121
2013,myall (d,{

d< - (mariahcarey,70) $ b names< - reorder(names,seq_along(names),order = TRUE)
year < - as.factor(year)
})

ggplot(d ,aes(names,count,fill = year))+
geom_bar(stat ='identity')+
theme(axis.text.x = element_text(angle = 45,hjust = 1))+实验室(fill ='year')


I have a question about plotting x axis in a certain order.

here is the sample data I am plotting:

  year                             names count
1 1998               allmylife - kcijojo    83
2 1997      doowopthatthing - laurynhill   196
3 1998      gettinjiggywitit - willsmith   231
4 2000 idontwanttomissathing - aerosmith    82
5 1998              imyourangel - rkelly   121
6 2013               myall - mariahcarey    70

Here is my code:

library(ggplot2)
setwd("C:/Users/Andrew/Desktop/music lyrics")
data = read.csv("summary.csv", header=FALSE, stringsAsFactors = FALSE)
names(data) = c('year', 'names', 'count')

ggplot(data, aes(names,count,  fill=year))+
geom_bar(stat='identity')+ 
theme(axis.text.x = element_text(angle = 90, hjust = 1))

And here is my current plot:

How do I sort the x axis such that it starts from 1998, 1999, 2000....2014? (instead of plotting them in random years)

解决方案

This will order the bars first by year, then alphabetically by name.

d <- read.csv(text="year,names,count
1998,               allmylife - kcijojo,    83
1997,      doowopthatthing - laurynhill,   196
1998,      gettinjiggywitit - willsmith,   231
2000, idontwanttomissathing - aerosmith,    82
1998,              imyourangel - rkelly,   121
2013,               myall - mariahcarey,    70")

d <- with(d, d[order(year, names), ])

d <- within(d, {
    names <- reorder(names, seq_along(names), order=TRUE)
    year <- as.factor(year)
})

ggplot(d, aes(names, count,  fill=year))+
  geom_bar(stat='identity')+ 
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +labs(fill='year') 

这篇关于ggplot以特定顺序绘制x轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆