Torvon Torvon - 1 month ago 6
R Question

ggplot2 plot question in R

I created a ggplot2 plot where I struggle with 2 things.

1) How to change the colors?

2) Why is the line missing between items 9 and 10?

cent <- rnorm(n=20, mean=5, sd=1)
num <- c(1:20)
groups2 <- c(rep("DSM Symptoms",9),rep("Non-DSM Symptoms",11))
data2 <- data.frame(num, cent, groups2)

ggplot(data2, aes(x=num, y=cent, fill=groups2, colour=groups2)) +
geom_line(color='#666666', size=0.7) +
geom_point() +
ylab('Strength Centrality') + xlab ('Symptoms') +
scale_x_reverse() +
scale_x_continuous(breaks = c(1:20)) +
coord_flip() +
theme_bw() +
theme(panel.grid.minor.y = element_blank())


screenshot

Answer

Working example:

ggplot(data2, aes(x=num, y=cent, colour=groups2)) + 
   geom_line(color='#666666', size=0.7) +
   geom_point() +
   ylab('Strength Centrality') + xlab ('Symptoms') + 
   scale_x_continuous(breaks = c(20:1)) +
   coord_flip() +
   theme_bw() + scale_color_manual(values=c("cyan","green"))+
   theme(panel.grid.minor.y = element_blank())

note the scale_color_manual(values=c(...)) and the absence of the fill parameter in the aesthetics section.

enter image description here

Note that if you want to reverse the ordering, you'd need to do something like scale_x_reverse(breaks=c(1:20)) since the scale_x_... options overwrite each other, with only the latest implemented.

Comments