如何在ggplot中将stat_summary拟合为矩形?

时间:2019-04-29 13:31:01

标签: r ggplot2

我想将stat_summary中的文本适合ggplot中的矩形,因此它会根据可用空间自动调整。

enter image description here

library(ggplot2)
category <- c('a','b','a','b','c','a','c')
values <- c(10,20,30,10,10,20,40)
dataset <- data.frame(category,values)
z = max(values)
stat_box_data <- function(y, upper_limit = z + 40) {
  return( 
    data.frame(
      y = upper_limit,
      label = paste('Contagem =', paste(length(y)), '\n',
                    'Média =', paste(round(mean(y), 1),'horas'), '\n',
                    'Desvio =', paste(round(sd(y), 1),'horas'), '\n',
                    'Mínimo =', paste(round(min(y),1),'horas'), '\n',
                    'Máximo =', paste(round(max(y),1),'horas'), '\n',
                    'Mediana =', paste(round(median(y),1),'horas'), '\n',
                    'Total =', paste(round(sum(y),1),'horas'), '\n'
      )
    )
  )
}
ggplot(dataset,aes(x=category, y=values))+
  geom_rect(aes(x=category, y=values),xmin = 0, xmax = 10, ymin = z+10, ymax = z+50,col = 'white') +
geom_boxplot(aes(x=category, y=values))+
stat_summary(fun.data = stat_box_data, geom = "text", hjust = 0.5,vjust = 0.85) +

geom_point(aes(x=category, y=values))+
facet_grid(. ~ category, space = "free", scales="free", margins=TRUE)

我有办法吗?

有此软件包:https://github.com/wilkox/ggfittext,但我无法使其与stat_summary一起使用!

1 个答案:

答案 0 :(得分:0)

ggfittext的最新开发版本(版本0.6.0.9003)使此操作变得容易得多。您可以通过以下方式安装它:

devtools::install_github("wilkox/ggfittext")

一旦安装此程序,便可以按照所需的方式自动调整文本大小:

library(ggplot2)
library(ggfittext)
packageVersion("ggfittext")
#> [1] '0.6.0.9003'

category <- c('a','b','a','b','c','a','c')
values <- c(10,20,30,10,10,20,40)
dataset <- data.frame(category,values)
z = max(values)
stat_box_data <- function(y, upper_limit = z + 40) {
  return( 
    data.frame(
      y = upper_limit,
      label = paste('Contagem =', paste(length(y)), '\n',
                    'Média =', paste(round(mean(y), 1),'horas'), '\n',
                    'Desvio =', paste(round(sd(y), 1),'horas'), '\n',
                    'Mínimo =', paste(round(min(y),1),'horas'), '\n',
                    'Máximo =', paste(round(max(y),1),'horas'), '\n',
                    'Mediana =', paste(round(median(y),1),'horas'), '\n',
                    'Total =', paste(round(sum(y),1),'horas'), '\n'
      )
    )
  )
}

ggplot(dataset,aes(x = category, y = values))+
  geom_rect(xmin = 0, xmax = 10, ymin = 50, ymax = 80, col = "white") +
  geom_boxplot() +
  geom_fit_text(stat = "summary", fun.data = "stat_box_data", ymin = 50, ymax = 80) +
  geom_point() +
  facet_grid(. ~ category, space = "free", scales = "free", margins = TRUE)

reprex package(v0.2.1)于2019-05-26创建