R 直方图

柱状图是使用不同高度的条形图对数据进行的图形显示。

柱状图用于汇总以区间尺度测量的离散或连续数据。


在 R 中创建柱状图

在 R 中,我们使用 hist() 函数创建柱状图。例如:

temperatures <- c(67 ,72 ,74 ,62 ,76 ,66 ,65 ,59 ,61 ,69 )

# histogram of temperatures vector
result <- hist(temperatures)

print(result)

输出

Create Histogram Output
创建柱状图

 

在上面的示例中,我们使用 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)

输出

Add TItle and Label to Histogram Output
为柱状图添加标题和标签

在上图中,我们可以看到我们已经为 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)

输出

Change Color of Histogram Output
更改柱状图颜色

在上面的示例中,我们使用 barplot() 内部的 col 参数来更改条形的颜色。

result <- hist(temperatures, 
  ...
  col = "red"
)

这里,col = "red" 将条形的颜色更改为红色。


R 中轴的范围

要在 R 中提供轴的范围,我们在 hist() 内部传递 xlabylab 参数。例如:

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)

输出

Provide Histogram Axes Range Output
带轴范围的柱状图

在上面的示例中,我们使用 hist() 内部的 xlimylim 参数分别提供 x 轴和 y 轴的范围。

result <- hist(temperatures, 
  ...
  xlim = c(50,100),
  ylim = c(0, 5))
)

这里,

  • x 轴范围从 50100
  • y 轴范围从 05
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战