柱状图设置坐标轴名称 |
您所在的位置:网站首页 › 柱状图修改坐标轴名称 › 柱状图设置坐标轴名称 |
笔者邀请您,先思考: 1 柱状图有什么作用?如何画柱状图? 柱状图(Bar chart)是使用不同长度的柱子来显示数据分布的图形。 一 基本柱状图1 描述因子类型的单个变量的数据分析 # 加载R包library(ggplot2)# 数据集 使用R语言内置的mtcars数据集# 基本柱状图ggplot(mtcars, aes(x=as.factor(cyl) )) + geom_bar()图形结果: 二 基本柱状图2 描述一个离散变量和一个连续变量的关系时,采用柱状图需要指定参数: stat=”identity” # 创建数据集data "A","B","C","D","E") , value=c(3,12,5,18,45))# 绘制柱状图ggplot(data, aes(x=name, y=value)) + geom_bar(stat = "identity")图形结果: 三 修改柱状图中柱子的颜色 可以通过以下方法来装饰柱子的颜色,从而让柱子更有鲜明对比性 # 1: 统一的颜色。颜色是用于边框,填充是用于内部ggplot(mtcars, aes(x=as.factor(cyl) )) + geom_bar(color="blue", fill=rgb(0.1,0.4,0.5,0.7) )# 2: 使用色调ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + geom_bar( ) + scale_fill_hue(c = 40)# 3: 使用RColorBrewerggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + geom_bar( ) + scale_fill_brewer(palette = "Set1")# 4: 使用greyscale:ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + geom_bar( ) + scale_fill_grey(start = 0.25, end = 0.75)# 5: 设置 manualyggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + geom_bar( ) + scale_fill_manual(values = c("red", "green", "blue") )第3种方法的图形结果: 四 删除图例和添加坐标轴名称 # 删除图例和添加坐标轴名称ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + geom_bar( ) + theme(legend.position = "none") + labs(x = "My class", y = "Value")图形结果: 五 柱状图水平摆放 # 柱状图水平摆放ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) + geom_bar() + coord_flip()图形结果: 六 自定义柱子的宽度 # 自定义柱子的宽度ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl))) + geom_bar(width=0.4)图形结果: 七 分组柱状图 在基本柱状图的基础上,根据实际数据的情况,设计和实现分组柱状图,分组柱状图包括平铺和堆叠,而堆叠柱状图又可以分为堆叠数量或者堆叠百分比。 # 加载ggplot2包library(ggplot2)# 创建数据集specie "sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )condition "normal" , "stress" , "Nitrogen") , 4)set.seed(360)value 12 , 0 , 15))data value)# 1 分组柱状图ggplot(data, aes(fill=condition, y=value, x=specie)) + geom_bar(position="dodge", stat="identity")# 2 堆叠柱状图ggplot(data, aes(fill=condition, y=value, x=specie)) + geom_bar( stat="identity")# 3 堆叠柱状图百分比ggplot(data, aes(fill=condition, y=value, x=specie)) + geom_bar( stat="identity", position="fill")分组柱状图结果: 堆叠柱状图结果: 堆叠柱状图百分比结果: 八 使用分面替代分组柱状图 使用faceting可以很好地替代分组柱状图。 # 分面柱状图ggplot(data, aes(y=value, x=specie, color=specie, fill=specie)) + geom_bar( stat="identity") + facet_wrap(~condition)公众号推荐:数据人才(ID:datarencai) 内容推荐 如何阅读论文? 论文管理工具,我用Zotero 一个数据人的2018 R中你应该学习的7种可视化 R的ggplot2包画折线图? 数据人论坛-R语言话题 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |