R语言 柱状图 geom_col 与 geom_bar 与geom_histogram(直方图)
Posted 基督徒Isaac
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了R语言 柱状图 geom_col 与 geom_bar 与geom_histogram(直方图)相关的知识,希望对你有一定的参考价值。
library(tidyverse)
#----案例1:绘制频数柱状图
data.frame(x = c("A", "B", "C"),
y = c(rep("negative", 7), rep("positive", 11))) %>%
ggplot(aes(x = x, fill = y)) + geom_bar() +
# coord_flip() + # 转为横向,从下到上
# scale_fill_manual( # 修改颜色
# values = c("white", "firebrick"),
# guide = FALSE) + # 图例
# scale_fill_manual(
# values = RColorBrewer::brewer.pal(n = 2, name = 'Blues')) +
# theme(
# legend.key = # legend加上边框线条
# element_rect(
# colour = "grey55")) +
# theme_bw() + # 外部主题
# theme(panel.grid = element_blank()) + # 内部主题
# scale_y_continuous(
# labels = scales::percent) # 坐标轴标签改为百分比
# labs(x = "Groups",
# y = "Percentage",
# fill = "Disease") +
annotate(
"text", x = 1, y = 3,
label = "50%",
colour = "white", fontface = "bold") + # 注释
annotate(
"text", x = 2, y = 4,
label = "67%",
colour = "white", fontface = "bold") +
annotate(
"text", x = 3, y = 4,
label = "67%",
colour = "white", fontface = "bold")
# https://zhuanlan.zhihu.com/p/443503128
# https://blog.csdn.net/g_r_c/article/details/19673625
# https://mp.weixin.qq.com/s/t6V09wXHeNdoXRR8BuSPiw
# https://www.delftstack.com/zh/howto/r/scale_y_continuous-in-r/
# https://thomasadventure.blog/zh/posts/ggplot2-percentage-scale/
# t <- mydata %>% table(); t
# tc <- t %>% cbind(row = t %>% rowSums()); tc
# tr <- tc %>% rbind(col = tc %>% colSums()); tr
#
# cbind(
# table(mydata),
# row = rowSums(
# table(mydata)))
#
# rbind(
# cbind(
# table(mydata),
# row = rowSums(
# table(mydata))),
# col = colSums(
# cbind(
# table(mydata),
# row = rowSums(
# table(mydata)))))
#----案例2:总结
# geom_col 需要提供x(分类变量)和y(数值变量,映射在y轴)
# geom_bar 只需要提供x,自动统计频数、频率,映射在y轴
# position = identity重叠,dodge分散,stack按频数堆积(左上→右下),fill按频率堆积
# Excel堆积左下→右上
# https://www.jianshu.com/p/57ec06c83fba
# ggplot2高效实用指南 https://www.jianshu.com/p/2dc81b91131e
# 透视、逆透视
# geom_col(分类变量,数值变量) = qplot(geom = "col")
data.frame(x = c("A", "B", "C"),
y = 1:18) %>%
ggplot(mapping = aes(x = x, y = y, fill = y)) + geom_col()
# geom_bar(分类变量) = stat_count
data.frame(x = c("A", "B", "C"),
y = c(rep("negative", 7), rep("positive", 11))) %>%
ggplot(aes(x = x, fill = y)) + geom_bar()
# geom_bar(分类变量,stat = "bin") = geom_histogram = stat_bin ≈ geom_freqpoly
ggplot(diamonds, aes(price, fill = cut)) +
geom_bar(stat = "bin")
ggplot(diamonds, aes(price, colour = cut)) +
geom_freqpoly()
geom_col 需要提供x(分类变量)和y(数值变量,映射在y轴)
geom_bar 只需要提供x,自动统计频数、频率,映射在y轴
position = identity重叠,dodge分散,stack按频数堆积(左上→右下),fill按频率堆积
ggplot2一页多图排版的简便方法:gridExtra::grid.arrange()
以及https://www.jianshu.com/p/c154ca35530b
以上是关于R语言 柱状图 geom_col 与 geom_bar 与geom_histogram(直方图)的主要内容,如果未能解决你的问题,请参考以下文章
R语言可视化包ggplot2绘制分组的条形图(bar plot柱状图)实战:多变量柱状图
FigDraw 5. SCI 文章绘图之柱状图 (Barplot)
R语言ggplot2可视化改变柱状图(条形图)的填充色实战:默认的颜色为灰色改变柱状图(条形图)的填充色设置每个柱子(条形)使用不同的色彩