R语言 使用ggplot2绘制柱状图
ggplot2是一个致力于数据可视化的R包。ggplot2包提高了图形的质量和美感(美学)。通过使用ggplot2,我们可以在RStudio中制作几乎所有类型的图形。
直方图是数字数据分布的一种近似表示。在直方图中,每个条形图将数字分为不同的范围。较高的条形图表明更多的数据落在该范围内。直方图显示连续样本数据的形状和分布。
直方图通过描述观测值在某些范围内出现的频率,使我们大致了解一个给定变量的概率分布。基本上,直方图用于显示特定变量的分布,而柱状图则用于比较变量。直方图绘制的是定量数据,数据的范围被归入区间,而条形图绘制的是分类数据。
geom_histogram() 函数是ggplot2模块中的一个内置函数。
使用方法
- 导入模块
- 创建数据框架
- 使用函数创建柱状图
- 显示图表
例1 :
set.seed(123)
# In the above line,123 is set as the
# random number value
# The main point of using the seed is to
# be able to reproduce a particular sequence
# of 'random' numbers. and sed(n) reproduces
# random numbers results by seed
df <- data.frame(
gender=factor(rep(c(
"Average Female income ", "Average Male incmome"), each=20000)),
Average_income=round(c(rnorm(20000, mean=15500, sd=500),
rnorm(20000, mean=17500, sd=600)))
)
head(df)
# if already installed ggplot2 then use library(ggplot2)
library(ggplot2)
# Basic histogram
ggplot(df, aes(x=Average_income)) + geom_histogram()
# Change the width of bins
ggplot(df, aes(x=Average_income)) +
geom_histogram(binwidth=1)
# Change colors
p<-ggplot(df, aes(x=Average_income)) +
geom_histogram(color="white", fill="red")
p
输出 :
例2 :
plot_hist <- ggplot(airquality, aes(x = Ozone)) +
# binwidth help to change the thickness (Width) of the bar
geom_histogram(aes(fill = ..count..), binwidth = 10)+
# name = "Mean ozone(03) in ppm parts per million "
# name is used to give name to axis
scale_x_continuous(name = "Mean ozone(03) in ppm parts per million ",
breaks = seq(0, 200, 25),
limits=c(0, 200)) +
scale_y_continuous(name = "Count") +
# ggtitle is used to give name to a chart
ggtitle("Frequency of mean ozone(03)") +
scale_fill_gradient("Count", low = "green", high = "red")
plot_hist
输出: