ggplot2做柱形图中排列顺序和堆积顺序的设置

本文分享自微信公众号 - 大数据建模笔记(bigdatamodeling)微信

在使用R语言的ggplot2包做柱形图时,有时须要设置排列和堆积的顺序。下面以自带的数据集diamonds做为演示。大数据

library(ggplot2)spa

set.seed(1234).net

# 从数据集 diamonds中抽取1000个样本3d

diam <- diamonds[sample(nrow(diamonds), 1000), ]blog

# 当不作任何设置时,此时的顺序按照变量clarity和color的原始顺序排列get

P <- ggplot(diam,  aes(x = clarity, fill=color))it

P <- P + geom_bar(stat='count')table

P <- P + labs(x = 'Family Size') + theme_bw()class

print(P)

 

# 1、设置柱形图的排列顺序

# 一、将x轴转化为因子,并将因子顺序设置为想要排列的顺序

P <- ggplot(diam,  

                     aes(x = factor(clarity,levels=c('SI2', 'I1', 'SI1', 

                                         'VS2', 'VS1',  'VVS2', 'VVS1', 'IF')),

                      fill=color))

P <- P + geom_bar(stat='count')

P <- P + labs(x = 'Family Size') + theme_bw()

print(P)

 

 

# 二、将x轴的刻度设置成为想要排列的顺序,效果和上面是同样的

P <- ggplot(diam, aes(x = clarity, fill=color)) 

P <- P + geom_bar(stat='count')

P <- P + scale_x_discrete(limits=c('SI2', 'I1', 'SI1', 'VS2', 

                                           'VS1',  'VVS2', 'VVS1', 'IF'))

P <- P + labs(x = 'Family Size') + theme_bw()

print(P)

 

# 三、按照高低顺序排列

clardf <- data.frame(table(diam$clarity))

names(clardf) <- c('clarity', 'freq')

library(dplyr)

clardf <- arrange(clardf, desc(freq))

P <- ggplot(diam, aes(x = factor(clarity, levels=clardf$clarity),fill=color))

P <- P + geom_bar(stat='count')

P <- P + labs(x = 'Family Size') + theme_bw()

print(P)

 

# 2、设置填充顺序

# 一、将填充变量转化为因子,并将因子顺序设置为想要填充的顺序

P <- ggplot(diam,  aes(x = clarity, 

                                        fill=factor(color, levels=c('J', 'I', 'H', 'G', 

                                                         'F', 'D', 'E'))))

P <- P + geom_bar(stat='count')

P <- P + labs(x = 'Family Size') + labs(fill="color") + theme_bw()

print(P)

 

# 二、将填充的刻度设置成为想要填充的顺序 ,效果和上面同样

P <- ggplot(diam, aes(x = clarity, fill=color))

P <- P + geom_bar(stat='count')

P <- P + scale_fill_discrete(limits=c('J', 'I', 'H', 'G', 'F', 'D', 'E'))

P <- P + labs(x = 'Family Size') + labs(fill="color") +  theme_bw()

print(P)

 

本文分享自微信公众号 - 大数据建模笔记(bigdatamodeling)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。