R绘图

【ggplot2】 不同情形添加平均值

2020-07-01  本文已影响0人  caokai001

参考:

ggplot2 cookbook
stat_summary 解读
https://ropensci.github.io/plotly/ggplot2/geom_abline.html

主要考虑下面几种情况:


操作:

1.对一个单变量添加均值垂线;

set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A", "B"), each = 200)), 
                  rating = c(rnorm(200), rnorm(200, mean = 0.8)))
head(dat)

ggplot(dat, aes(x=rating)) + geom_histogram(binwidth=.5,colour="black", fill="white")


## 添加单组x变量平均线
ggplot(dat, aes(x=rating)) +
  geom_histogram(binwidth=.5, colour="black", fill="white") +
  geom_vline(aes(xintercept=mean(rating, na.rm=T)),   # 忽略缺失值
             color="red", linetype="dashed", size=1)
image.png

2.对多个分组变量添加均值垂线;

## 分组变量 x 轴平均线
cdat <- as_tibble(dat) %>%  group_by(cond) %>% dplyr::summarise(rating.mean =mean(rating))
ggplot(dat, aes(x = rating, fill = cond)) + geom_histogram(binwidth = 0.5, 
                                                           alpha = 0.5, position = "identity")+
  geom_vline(dat=cdat,aes(xintercept=rating.mean,colour = cond),
             linetype = "dashed",size=2)
image.png

3.对分面变量添加均值垂线;

## 分面变量 x 轴平均线
ggplot(dat, aes(x = rating)) + geom_histogram(binwidth = 0.5, 
                                              colour = "black", fill = "white") + facet_grid(cond ~ 
                                                                                               .)+
  geom_vline(dat=cdat,aes(xintercept=rating.mean,colour = cond),
             linetype = "dashed",size=2)

image.png

4. 多个分组变量添加均值

######### 分组 y 平均值
library(Hmisc)
g <- ggplot(mtcars,aes(cyl, mpg)) + geom_point()
g + stat_summary(fun.data = "mean_cl_boot", color = "red", size = 2)
g + stat_summary(fun = "mean", color = "red", size = 2, geom = "point") 

image.png

5.对分面变量添加均值水平线

########## 分面 y 平均值
p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_wrap(~ cyl)
cdat <- mtcars %>% group_by(cyl) %>% dplyr::summarise(m=mean(wt))
p + geom_hline(data=cdat,aes(yintercept=m))
image.png

Tips : 画局部放大图

目前想到用于三维交互热图 不同分辨率可视化上很方便。
参考:

image.png
qplot(x, y, data = diamonds, na.rm = TRUE)
last_plot() + xlim(3, 11) + ylim(3, 11)
last_plot() + xlim(4, 10) + ylim(4, 10)
last_plot() + xlim(4, 5) + ylim(4, 5)
last_plot() + xlim(4, 4.5) + ylim(4, 4.5)
last_plot() + geom_abline(colour = "red")
image.png

欢迎评论留言~😀

上一篇下一篇

猜你喜欢

热点阅读