仅在ggplot2

时间:2019-05-01 00:20:16

标签: r ggplot2 intervals

c1 <- c("p2","p3","p1","p2","p1","p3","p4","p4","p4","p1","p1","p2","p2","p3","p4","p2","p1","p4","p3","p3")
c2 <- c(41,146,79,107,131,127,32,88,119,148,32,65,36,23,44,76,100,98,121,104)
df <- data.frame(c1=c1, c2=c2)
c <- mutate(df, c2.intervals = cut(c2, breaks = c(0, 30, 50, 70,120,150)))
ggplot(aes(x = c2.intervals, fill = c1), data=c) + geom_histogram(stat="count")

这将显示x轴上所有间隔的文本。我想在绘制所有垃圾箱时显示某些级别的文本,例如(30,50](70,120]。换句话说,是否有一种简单的方法可以在ggplot2中隐藏c2.intervals某些级别的文本?

1 个答案:

答案 0 :(得分:1)

你的意思是这样吗?

变体1(手动)

1

ggplot(aes(x = c2.intervals, fill = c1), data = c) + 
    geom_histogram(stat = "count") +
    scale_x_discrete(labels = c("", "(30,50]", "", "(70,120))", ""))

变体2(每n个显示一次)

1

xlabels <- levels(c$c2.intervals)
xlabels[seq(1, length(xlabels), 2)] <- ""

ggplot(aes(x = c2.intervals, fill = c1), data = c) + 
    geom_histogram(stat = "count") +
    scale_x_discrete(labels = xlabels)

数据

library(dplyr)
library(ggplot2)

c1 <- c("p2","p3","p1","p2","p1","p3","p4","p4","p4","p1","p1","p2","p2","p3","p4","p2","p1","p4","p3","p3")
c2 <- c(41,146,79,107,131,127,32,88,119,148,32,65,36,23,44,76,100,98,121,104)
df <- data.frame(c1 = c1, c2 = c2)
c <- mutate(df, c2.intervals = cut(c2, breaks = c(0, 30, 50, 70, 120, 150)))