geom_dotplot,带有文本而不是点

时间:2018-01-31 15:04:41

标签: r ggplot2

在下面的地图中,您如何使用name列定义的文字标签替换每个点?

library(ggplot2)
library(ggrepel)

name <- c(
  "2", "5", "1", "8", "6", "7", "4", "10", "9", "3",
  "H", "U", "S", "F", "R", "A", "T", "F", "M", "S"
)
Measure <- c(
  0.44, 0.36, 0.30, 0.29, 0.24, 0.22, 0.20, 0.16, 0.14, 0.10,
  0.11, 0.07, 0.07, 0.04, 0.04, 0.04, -0.01, -0.01, -0.02, -0.31
)
Variable <- c(rep("Sample", times = 10), rep("Variable", times = 10))
example <- data.frame(name, Measure, Variable)

ggplot(example, aes(x = Measure)) +
  geom_dotplot(binwidth = 0.05, dotsize = 0.5) +
  theme_bw(base_size = 24) +
  facet_wrap(~ Variable, nrow = 1) +
  coord_flip()

dotplot

1 个答案:

答案 0 :(得分:4)


创建虚假数据:

set.seed(42)
d <- data.frame(
  x = c(rnorm(20, mean = 0), rnorm(20, mean = 0.25), rnorm(20, mean = 0.5)),
  label = sample(letters, 60, replace = TRUE),
  group = sample(1:3, 60, replace = TRUE)
)
head(d)
#>            x label group
#> 1  1.3709584     j     3
#> 2 -0.5646982     k     3
#> 3  0.3631284     o     1
#> 4  0.6328626     p     1
#> 5  0.4042683     s     3
#> 6 -0.1061245     k     3

使用graphics :: hist来存储值:

d_hist <- hist(d$x, plot = FALSE)
d$x_bin <- cut(d$x, breaks = d_hist$breaks, label = FALSE)
d$x_mid <- d_hist$mids[d$x_bin]
d$y <- 1

使用dplyr按柱状图bin和group堆叠值:

library(dplyr)
d %<>% group_by(group, x_bin) %>% mutate(y = cumsum(y))
head(d)
#> # A tibble: 6 x 6
#> # Groups:   group, x_bin [4]
#>        x label group x_bin  x_mid     y
#>    <dbl> <fct> <int> <int>  <dbl> <dbl>
#> 1  1.37  j         3     5  1.50   1.00
#> 2 -0.565 k         3     3 -0.500  1.00
#> 3  0.363 o         1     4  0.500  1.00
#> 4  0.633 p         1     4  0.500  2.00
#> 5  0.404 s         3     4  0.500  1.00
#> 6 -0.106 k         3     3 -0.500  2.00

绘制直方图:

library(ggplot2)
ggplot() +
  geom_text(
    data = d,
    mapping = aes(
      x = x_mid,
      y = y,
      label = label
    ),
    size = 6
  ) +
  coord_flip() +
  facet_wrap(~ group) +
  theme_bw(base_size = 20) +
  theme(panel.grid = element_blank()) +
  labs(x = "Measure", y = "Count")