R HISTOGRAM EXAMPLE QUICK REFERENCE

这篇博客展示了如何利用R语言的ggplot2库创建数据可视化图表。首先,通过`tidyverse`包整理数据,然后使用`ggplot`和`geom_histogram`绘制直方图,将数据按性别分组并使用不同颜色区分。此外,还用`facet_wrap`进行图例分面,以及调整颜色映射。最后,使用`gghistogram`函数简化绘图过程,并改变颜色以突出性别差异。
摘要由CSDN通过智能技术生成
library(tidyverse)
theme_set(
  theme_bw() +
    theme(legend.position = "top")
)
head(iris, 3)
iris.gathered <- iris %>%
  as_data_frame() %>%
  gather(key = "variable", value = "value",
         -Sepal.Length, -Species)

head(iris.gathered, 3)
ggplot(iris.gathered, aes(x = value, y = Sepal.Length)) +
  geom_point(aes(color = Species)) +
  facet_wrap(~variable)+
  scale_color_viridis_d()

在这里插入图片描述

set.seed(1234)
wdata = data.frame(
  sex = factor(rep(c("F", "M"), each=200)),
  weight = c(rnorm(200, 55), rnorm(200, 58))
)

head(wdata, 4)
hist(wdata$weight, breaks = 30, col = "steelblue", frame = FALSE)

在这里插入图片描述

library(ggplot2)
theme_set(theme_bw())
# Basic plot
ggplot(wdata, aes(x = weight)) +
  geom_histogram(bins = 30) 

# Change fill color by sex group
ggplot(wdata, aes(x = weight)) +
  geom_histogram(aes(fill = sex), bins = 30, alpha = 0.5,
                 position = position_dodge()) +
  scale_fill_viridis_d() 

在这里插入图片描述

library(ggpubr)

# Basic plots
gghistogram(wdata, x = "weight", fill = "steelblue", alpha = 1)

# Change color by sex group
gghistogram(
  wdata, x = "weight", color = "sex",
  palette = c("#00AFBB", "#E7B800")
)

在这里插入图片描述
原文链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值