user3022875 user3022875 - 10 days ago 5
R Question

coloring with scale_color_manual

I have a data frame that look like this:

d= data.frame(Name = c("B","A","A","B","A","B"),
Group= c("one","one","two","two","three","three"),
value=c(.5,.6,.7,.8,.4,.2))
d

Name Group value
1 B one 0.5
2 A one 0.6
3 A two 0.7
4 B two 0.8
5 A three 0.4
6 B three 0.2


when I plot it looks like this. notice where the A line is

ggplot(d,
aes(x=factor(Group),
y= value,
group= Name , color =Name)) +
geom_point()+geom_line()


enter image description here

Now I want to color the lines using scale color manual like this:

library(RColorBrewer)
n <- 60
qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',]
col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))

ggplot(d,
aes(x=factor(Group),
y= value,
group= Name , color =Name)) +
geom_point()+geom_line() +
scale_color_manual(name="name",
labels = unique(d$Name)
,
values= col_vector[14:(14+(length(unique(d$Name)) )-1 )]
)


that produces this image where the "A" line is not correct. It is now the "B" line. How can I scale color manual to change the output using the colors in col_vector but keep the correct output?

enter image description here

Answer

Function unique() returns values in the order as they are located in your dataframe.

unique(d$Name)
[1] B A
Levels: A B

So you should use function levels().

levels(d$Name)
[1] "A" "B"

If variable is not stored as factor, you can add sort() function.

sort(unique(d$Name))
[1] "A" "B"
Comments