柱状图是使用不同高度的条形图对数据进行的图形显示。
柱状图用于汇总以区间尺度测量的离散或连续数据。
在 R 中创建柱状图
在 R 中,我们使用 hist()
函数创建柱状图。例如:
temperatures <- c(67 ,72 ,74 ,62 ,76 ,66 ,65 ,59 ,61 ,69 )
# histogram of temperatures vector
result <- hist(temperatures)
print(result)
输出

在上面的示例中,我们使用 hist()
函数创建了 temperatures 向量的柱状图。
我们上面创建的柱状图简单明了,我们可以在柱状图上添加很多东西。
在 R 中为柱状图添加标题和标签
要在 R 中为我们的柱状图添加标题和标签,我们分别在 hist()
函数内部传递 main
和 xlab 参数。例如:
temperatures <- c(67 ,72 ,74 ,62 ,76 ,66 ,65 ,59 ,61 ,69 )
# histogram of temperatures vector
result <- hist(temperatures,
main = "Histogram of Temperature",
xlab = "Temperature in degrees Fahrenheit"
)
print(result)
输出

在上图中,我们可以看到我们已经为 temperatures 向量的柱状图添加了标题和标签。
hist(temperatures,
main = "Maximum Temperatures in a Week",
xlab = "Temperature in degrees Fahrenheit")
这里,
main
- 添加标题"一周最高气温"
xlab
- 添加标签"华氏温度"
在 R 中更改柱状图的条形颜色
在 R 中,我们在 hist()
内部传递 col
参数来更改条形的颜色。例如:
temperatures <- c(67 ,72 ,74 ,62 ,76 ,66 ,65 ,59 ,61 ,69 )
# histogram of temperatures vector
result <- hist(temperatures,
main = "Histogram of Temperature",
xlab = "Temperature in degrees Fahrenheit",
col = "red")
print(result)
输出

在上面的示例中,我们使用 barplot()
内部的 col
参数来更改条形的颜色。
result <- hist(temperatures,
...
col = "red"
)
这里,col = "red"
将条形的颜色更改为红色。
R 中轴的范围
要在 R 中提供轴的范围,我们在 hist()
内部传递 xlab
和 ylab
参数。例如:
temperatures <- c(67 ,72 ,74 ,62 ,76 ,66 ,65 ,59 ,61 ,69 )
# histogram of temperatures vector
result <- hist(temperatures,
main = "Histogram of Temperature",
xlab = "Temperature in degrees Fahrenheit",
col = "red",
xlim = c(50,100),
ylim = c(0, 5))
print(result)
输出

在上面的示例中,我们使用 hist()
内部的 xlim
和 ylim
参数分别提供 x 轴和 y 轴的范围。
result <- hist(temperatures,
...
xlim = c(50,100),
ylim = c(0, 5))
)
这里,
- x 轴范围从 50 到 100
- y 轴范围从 0 到 5