如何用新行替换重叠的x轴标签?

问题描述:

在x轴上绘制长文本因子时,ggplot不能很好地完成工作.我想换一个新行,以便更清晰(因此,下图中的红色标记标签应向下一行).

When plotting long text factors in the x axis ggplot does not make a very good job. I want to alternate a new line so it is more legible (so the red marks labels in the picture below should be a line down).

我在此处的评论中找到了答案,但是可以'努力工作.代码是:

I've found an answer to this in the comments here but can't make work. The code is:

scale_x_discrete( labels = function( labels ) { 
fixedLabels <- c() for ( l in 1:length( labels ) ) { 
fixedLabels <- c( fixedLabels, paste0( ifelse( l %% 2 == 0, '', '\n' ), labels[l] ) ) } return( fixedLabels ) } )

测试数据:

library(ggplot2)

Group = c("D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D10", "D11", "D12", "D13", "D14")
x = c(141, 57, 38, 18, 13, 7, 5, 4, 2, 2, 1, 1, 1, 1)

dat <- data.frame(
  Group = Group,
  x = x,
  stringsAsFactors=TRUE
)

dat <- dat[order(dat$x, decreasing=TRUE), ]
dat$Group <- factor(dat$Group, levels=dat$Group[order(dat$x, decreasing=TRUE)])
cum = sum(dat$x)
dat$cum <- 100*(dat$x)/cum
dat$cum = cumsum(dat$cum)

> dat
   Group   x       cum
1     D1 141  48.45361
2     D2  57  68.04124
3     D3  38  81.09966
4     D4  18  87.28522
5     D5  13  91.75258
6     D6   7  94.15808
7     D7   5  95.87629
8     D8   4  97.25086
9     D9   2  97.93814
10   D10   2  98.62543
11   D11   1  98.96907
12   D12   1  99.31271
13   D13   1  99.65636
14   D14   1 100.00000

 ggplot(dat, aes(x=Group)) +
  geom_bar(aes(y=x), fill="light blue", stat="identity") +
  stat_count(aes(label = x), geom = "text", vjust=-0.3, size=3.5) + 
  geom_point(aes(y=cum)) +
  geom_path(aes(y=cum, group=1))

这是您在评论中发现的一个巧妙的小技巧!它确实有效,只是确保您观看语法:l!= 1,尽管它看起来与非常类似:

That's a neat little trick you found in the comments! It does work, just make sure you watch your syntax: l != 1 although it looks very similar:

ggplot(dat, aes(x = Group)) +
  geom_bar(aes(y = x), fill = "light blue", stat = "identity") +
  stat_count(aes(label = x), geom = "text", vjust = -0.3, size = 3.5) + 
  geom_point(aes(y = cum)) +
  geom_path(aes(y = cum, group = 1)) +
  scale_x_discrete(labels = function(labels) {
    fixedLabels <- c()
    for (l in 1:length(labels)) {
      fixedLabels[l] <- paste0(ifelse(l %% 2 == 0, '', '\n'), labels[l])
    }
    return(fixedLabels)
  })

注意:您可以选择更简洁地重写语法(在这里我使用i以避免混淆并可能使其更具可读性):

Note: You could choose to rewrite the syntax more succinctly (here I'm using i to avoid confusion and maybe make it more readable):

ggplot(dat, aes(x = Group)) +
  geom_bar(aes(y = x), fill = "light blue", stat = "identity") +
  stat_count(aes(label = x), geom = "text", vjust = -0.3, size = 3.5) + 
  geom_point(aes(y = cum)) +
  geom_path(aes(y = cum, group = 1)) +
  scale_x_discrete(labels = function(labels) {
    sapply(seq_along(labels), function(i) paste0(ifelse(i %% 2 == 0, '', '\n'), labels[i]))
  })