#条形图通过垂直的或水平的条形展示了分类变量的分布(频数)。
#通过ggplot2包,使用代码形式为:
#ggplot(data, aes(x = catvar) + geom_bar())
#data为数据框,catvar为分类变量
#使用了vcd包中的Arthritis数据框
library(ggplot2)
library(vcd)
#简单的条形图
print(ggplot(Arthritis, aes(x = Improved)) + geom_bar() +
labs(title = "simple bar chart",
x = "Improvement",
y = "frequency"))
#水平条形图主要用于展示类别数据,通过比较不同类别条形的长度,直观地展示各类别数量上的差异。
print(ggplot(Arthritis, aes(x = Improved)) + geom_bar() +
labs(title = "horizontal",
x = "Improvement",
y = "Frequency") +
coord_flip())
堆积条形图、分组条形图(簇状条形图)、填充条形图:
#使用table()函数生成变量的交叉表
#table(Arthritis$Improved, Arthritis$Treatment)
library(ggplot2)
#堆积条形图:用于比较不同类别的数据之间关系的可视化工具,能够显示多个变量堆叠在同一列中,并且将它们在同一列中的比较分层展示
print(ggplot(Arthritis,aes(x = Treatment, fill =Improved)) +
geom_bar(position = "stack") +
labs(title = "Stacked BarChart",
x = "Treatment",
y = "Frequency"))
#分组条形图以不同分组高度相同的长方形的宽度为变量的统计图表,每个分组中的柱子使用不同的颜色或者相同颜色不同透明的方式区别各个分类,各个分组之间需要保持间隔。
print(ggplot(Arthritis,aes(x = Treatment, fill =Improved)) +
geom_bar(position = "dodge") +
labs(title = "Grouped BarChart",
x = "Treatment",
y = "Frequency"))
#填充条形图常用于表示数据随时间或其他变量的变化情况,特别是当数据变化趋势或波动特别明显时。
print(ggplot(Arthritis,aes(x = Treatment, fill =Improved)) +
geom_bar(position = "fill") +
labs(title = "Fill BarChart",
x = "Treatment",
y = "Proportion"))
均值条形图:
#均值条形图用于展示每个类别的均值或中位数等中心趋势的估计值,通常以条形的长度或高度来表示。
library(dplyr)
states <- data.frame(state.region, state.x77)
plotdata <- states %>%
group_by(state.region) %>%
summarize(mean = mean(Illiteracy))
plotdata
print(ggplot(plotdata, aes(x = reorder(state.region, mean), y = mean)) +
geom_bar(stat = "identity") +
labs(x = "Region",
y = " ",
title = "Mean Illiteracy Rate"))
带误差的均值条形图:
#带误差的均值条形图在条形图中加入了误差条,通常用于展示估计值的不确定度。误差条通常表示数据的置信区间或标准误差,通过这种方式,可以更准确地理解数据的波动和变化情况。
library(dplyr)
states <- data.frame(state.region, state.x77)
plotdata <- states %>%
group_by(state.region) %>%
summarize(n = n(),
mean = mean(Illiteracy),
se = sd(Illiteracy) / sqrt(n))
print(ggplot(plotdata, aes(x = reorder(state.region, mean), y = mean)) +
geom_bar(stat = "identity", fill = "skyblue") +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = 0.2) +
labs(x = "Region",
y = " ",
title = "Mean Illiteracy Rate",
subtitle = "with standard error bars"))