2

I have the following data.frame:

ef2 <- data.frame(X1=c(50,100,'bb','aa'), X2=c('A','A','B','B'), value=c(1,4,3,6))

I want to create two plots, one for each group in X2.

Here is the code I have and the plot obtained:

ggplot(data=ef2, aes(x=X1, y=value, group=X2)) +
  facet_grid(.~X2, scales="free_x") +
  geom_line(size=1) +
  geom_point(size=3) +
  xlab('') +
  ylab('Y')

enter image description here

The problem is that the x-axis is ordered alphabetically and I don't know how to fix it. I have tried adding scale_x_discrete, but I don't know how to separate groups. You can see the plot I obtained adding this parameter in the following link:

ggplot(data=ef2, aes(x=X1, y=value, group=X2)) +
  facet_grid(.~X2, scales="free_x") +
  geom_line(size=1) +
  geom_point(size=3) +
  xlab('') +
  ylab('Y') +
  scale_x_discrete(limits=ef2$X1)

enter image description here

Edited: I can't change ef2 data.frame. I've tried ordering factors in another data.frame:

ef2 <- data.frame(X1=c(50,100,'bb','aa'), X2=c('A','A','B','B'), value=c(1,4,3,6))
ef2$X1 <- as.character(ef2$X1)
nou <- data.frame(X1=factor(ef2$X1), levels=ef2$X1, X2=ef2$X2, value=ef2$value)

But it doesn't work.

Marta
  • 75
  • 7
  • Google "ggplot order factor levels" and you will find a lot of other posts on this topic. – Henrik Jun 14 '16 at 09:45
  • My problem is not to order factor levels. My problem is how to use my data.frame to create another one with ordered factors. – Marta Jun 14 '16 at 10:35

1 Answers1

0

This worked for me but I am not sure if it is exactly what you need:

ef2 <- data.frame(X1=factor(c('50','100','bb','aa'), levels = c('50','100','bb','aa')), X2=c('A','A','B','B'), value=c(1,4,3,6))

ggplot(data=ef2, aes(x=X1, y=value, group=X2)) +
  facet_grid(.~X2, scales="free_x") +
  geom_line(size=1) +
  geom_point(size=3) +
  xlab('') +
  ylab('Y')

enter image description here

According to this post: Avoid ggplot sorting the x-axis while plotting geom_bar() ggplot orders automatically unless you provide an already orderd factor.

Update:

The code you use has an error. levels is an argument of the factor function. Try this:

ef2 <- data.frame(X1=c(50,100,'bb','aa'), X2=c('A','A','B','B'), value=c(1,4,3,6))
ef2$X1 <- factor(ef2$X1, levels = unique(ef2$X1))
Community
  • 1
  • 1
Alex
  • 4,925
  • 2
  • 32
  • 48
  • Thank you very much for your answer! The problem is that I can't change the ef2 data.frame. I've tried to create a new one: `ef2 <- data.frame(X1=c(50,100,'bb','aa'), X2=c('A','A','B','B'), value=c(1,4,3,6)) ef2$X1 <- as.character(ef2$X1) nou <- data.frame(X1=factor(ef2$X1), levels=ef2$X1, X2=ef2$X2, value=ef2$value)` But it doesn't work – Marta Jun 14 '16 at 10:39
  • Perfect, thank you! – Marta Jun 14 '16 at 16:47