Alexander Alexander - 1 year ago 145
R Question

Setting order of scale_x_discrete when there are repeated levels

I want to make usual geom_point plot using ggplot. But some of x values are repeated and I want to repeat them again in the x axis. So I tried

and followed the example at here change-the-order-of-a-discrete-x-scale but I was not able to do what I want.

Here is my example

x = c(seq(1,4),seq(2,4))
y= (seq(1,7))

df <- data.frame(x,y,ex)
x y ex
1 1 1 ex1
2 2 2 ex1
3 3 3 ex1
4 4 4 ex1
5 2 5 ex2
6 3 6 ex2
7 4 7 ex2

ggplot(df, aes(x=factor(x),y=y)) +
geom_point(size=4) +

enter image description here

with discrete x repeat values, the repeated x axis values is not shown. How can repeat
values again after
in the x axis?


Answer Source

Because you want not x but a combination of repeat and x as x-axis, it is a natural idea to give aes(x) the combination.

ggplot(df, aes(x = interaction(x, ex), y = y)) + 
  geom_point(size=4)  +
  scale_x_discrete(labels = df$x)

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download