2

I made the following code, which reads a table (with 10 columns) and generates a line graph. The problem is, it reorders the legend alphabetically. How to avoid reordering and keep the original ordering? I already read how to avoid it by removing the breaks but I could not sort it out.

Any idea would be great.

Appreciate!

qw is a dataframe.

qw %>% 
  add_rownames() %>% 
  gather(reading, value, -rowname) %>% 
  group_by(rowname) %>% 
  mutate(x=1:n()) %>% 
  ggplot(aes(x=x, y=value, group=rowname)) +
  geom_line(aes(color=rowname), line = 2.5, cex = 1.05) + 
  labs(colour= "Methods",x="XXXX", y="YYYY") + 
  theme(axis.text=element_text(size=14), 
        axis.title=element_text(size=14)) + 
  xlim(min=1, max=10)+ 
  scale_x_continuous(breaks=c(1,2,3,4,5,6,7,8,9,10)) + 
  theme(legend.text=element_text(size=12)) + 
  geom_point() 
Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Ester Silva
  • 670
  • 6
  • 24
  • 2
    make `qw$rowname` a `factor` and set the `levels` to your desired order. see `?factor()` – Nate May 16 '18 at 13:05
  • If the column are characters then it has no ordering. To have ordering it needs to be a factor – Jack Brookes May 16 '18 at 13:08
  • @Nate, I am not fully following your comment, May you detail it? Thanks – Ester Silva May 16 '18 at 13:53
  • 1
    To elaborate on Nate's point, you can add add `mutate(rowname = factor(rowname, levels = c("label 1", "label 2", ...) %>%` after `add_rownames() %>%`. – Z.Lin May 16 '18 at 14:08
  • Possible duplicate of [How to reorder a legend in ggplot2?](https://stackoverflow.com/questions/26872905/how-to-reorder-a-legend-in-ggplot2) – GGamba May 17 '18 at 13:55

1 Answers1

1

Hopefully, this helps...

library(tidyverse)

# built-in data is nice for SO and I don't have 'qw'
data("ChickWeight") 
cw <- ChickWeight

# make a new character column 'cw$diet_name', similar to 'qw$rownames'
dc <- LETTERS[1:4] %>% set_names(1:4)
cw$diet_name <- dc[cw$Diet] %>%
    factor(levels = c("C", "B", "D", "A")) # set legend order with levels

ggplot(cw, aes(Time, weight, color = diet_name, group = Chick)) +
    geom_line() # colors are in custom order!

enter image description here

Let me know if it isn't clear :)

Nate
  • 10,361
  • 3
  • 33
  • 40