HappyPy
HappyPy

Reputation: 10697

showing the text of only a few interval levels in 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)))
ggplot(aes(x = c2.intervals, fill = c1), data=c) + geom_histogram(stat="count")

This shows the text for all intervals in the x axis. I would like to show the text of some of the levels, say (30,50], and (70,120], while plotting all bins. In other words is there an easy way to hide the text of some levels of c2.intervals in ggplot2?

Upvotes: 0

Views: 130

Answers (1)

Roman
Roman

Reputation: 4989

You mean like this?


Variant 1 (manual)

1

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

Variant 2 (show every n-th)

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)

Data

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)))

Upvotes: 1

Related Questions