登录
首页精彩阅读R语言条形图(柱状图)
R语言条形图(柱状图)
2017-06-19
收藏

R语言条形图(柱状图)

条形图代表在与条成比例的变量的值的长度矩形条数据。R使用函数barplot()来创建柱状图。R能够绘制柱状图垂直和水平条。在柱状图中每个条都可以显示不同的颜色。

语法

创建一个条形图在R中的基本语法是:

barplot(H,xlab,ylab,main, names.arg,col)

以下是所使用的参数的说明:

H - 是包含在柱状图中使用数值的矢量或矩阵。

xlab - 是标签为X轴。

ylab - 是标签为Y轴。

main - 是柱状图的标题名称

names.arg - 是出现在每个条的向量名称。

col - 用于给出在图中的条状的颜色。

示例

只用输入向量和每个栏的名称创建一个简单的柱状图

下面的脚本将创建并保存柱状图到R的当前工作目录。

# Create the data for the chart.
H <- c(7,12,28,3,41)

# Give the chart file a name.
png(file = "barchart.png")

# Plot the bar chart.
barplot(H)

# Save the file.
dev.off()

当我们上面的代码执行时,它产生以下结果:

柱状图标签,标题和颜色

柱状图特征可以通过添加更多的参数进行扩展。 The main参数用于添加标题。col参数用于颜色添加到柱状图。args.name 是具有值作为输入矢量的相同数量,用来描述每个条的含义。

示例

下面的脚本将创建并保存柱状图到R的当前工作目录。

# Create the data for the chart.
H <- c(7,12,28,3,41)
M <- c("Mar","Apr","May","Jun","Jul")

# Give the chart file a name.
png(file = "barchart_months_revenue.png")

# Plot the bar chart.
barplot(H,names.arg=M,xlab="Month",ylab="Revenue",col="blue",
main="Revenue chart",border="red")

# Save the file.
dev.off()

当我们上面的代码执行时,它产生以下结果:

柱状图和堆叠条形图

我们可以用一个矩阵的输入值来创建条形图的条和叠层中的每个条组。

两个以上的变量表示为它用于创建组柱状图和堆积条形图的矩阵。

# Create the input vectors.
colors <- c("green","orange","brown")
months <- c("Mar","Apr","May","Jun","Jul")
regions <- c("East","West","North")

# Create the matrix of the values.
Values <- matrix(c(2,9,3,11,9,4,8,7,3,12,5,2,8,10,11),nrow=3,ncol=5,byrow=TRUE)

# Give the chart file a name.
png(file = "barchart_stacked.png")

# Create the bar chart.
barplot(Values,main="total revenue",names.arg=months,xlab="month",ylab="revenue",col=colors)

# Add the legend to the chart.
legend("topleft", regions, cex=1.3, fill=colors)

# Save the file.
dev.off()

当我们上面的代码执行时,它产生以下结果:

数据分析咨询请扫描二维码

客服在线
立即咨询