How to make independent vectors next to each other within a group?

I am learning ggplot. I made a plot that I'm almost happy with and there is one detail to fix.

My details are here:

gIN <- c("A_1","A_2","A_3","A_4","B_1","B_2","B_3","B_4","B_5","C_1","C_2","C_3")
bc <- c(1219.79, 1486.84, 1255.80, 941.87, 588.19, 304.02, 279.71, 373.40, 179.89, 385.02, 218.76, 423.33)
bc2 <- c(319.79, 186.84, 125.80, 94.87, 1008.19, 314.02, 500.71, 600.40, 900.89, 38.02, 1000.76, 500.33)
group <- c("A","A","A","A","B","B","B","B","B","C","C","C")

ex <- data.frame("gIN" = gIN, "bc" = bc, "bc2"=bc2, "group" = group)

      

I'm trying to show vectors bc and bc2 next to each other, but they overlap the way I built the command, here:

ggplot(data=ex) + facet_grid(. ~group, scales="free") + 
  geom_line(aes(x=group, y=bc,group=group,colour="bc")) + geom_point(aes(x=group, y=bc,colour="bc")) + 
  geom_line(aes(x=group, y=bc2,group=group,colour="bc2")) + geom_point(aes(x=group, y=bc2,colour="bc2")) 

      

Plot:

http://i.imgur.com/od6xVRT.png

As you can see, group A looks fine because the blue and red lines are separate, but when the values โ€‹โ€‹overlap (as in groups B and C), it becomes clear to see the data.

Does anyone know how to change the command so that each vector is side-by-side instead of overlaid?

Thank.

+3


source to share


1 answer


Below is a possible solution related to permutation of data using melt()

and using the categorical X-axis to separate data types "bc" and "bc2". Another advantage is that the build code itself is easier to write.

library(ggplot2)
library(reshape2)

mdat = melt(ex, id.vars=c("gIN", "group"), value.vars=c("bc", "bc2"))

head(mdat)
#   gIN group variable   value
# 1 A_1     A       bc 1219.79
# 2 A_2     A       bc 1486.84
# 3 A_3     A       bc 1255.80
# 4 A_4     A       bc  941.87
# 5 B_1     B       bc  588.19
# 6 B_2     B       bc  304.02


p = ggplot(mdat, aes(x=variable, y=value, colour=variable)) + 
    geom_point() + 
    geom_line() + 
    facet_grid(. ~ group)

      



enter image description here

0


source







All Articles