Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify different palettes and line size within a single ggplot2 plot

Tags:

r

ggplot2

I'm displaying four distributions within the same ggplot2 graph with the following code (data downloadable there: https://www.dropbox.com/s/l5j7ckmm5s9lo8j/1.csv?dl=0):

require(reshape2)
library(ggplot2)
library(RColorBrewer)

fileName = "./1.csv" # downloadable there: https://www.dropbox.com/s/l5j7ckmm5s9lo8j/1.csv?dl=0

mydata = read.csv(fileName,sep=",", header=TRUE)

dataM = melt(mydata,c("bins"))

ggplot(data=dataM, aes(x=bins, y=value, colour=variable)) +
xlab("bins") + ylab("freq") + geom_line(size = .5, alpha = .9) +
scale_colour_brewer(type = "qual", palette = 7) +
geom_line(size = .5, alpha = .9) +
theme_bw() +
theme(plot.background = element_blank()
,panel.grid.minor = element_blank()
,axis.line = element_blank()
,legend.key = element_blank()
,legend.title = element_blank()) +
scale_y_continuous(expand=c(0,0)) + 
scale_x_continuous(expand=c(0,0))

enter image description here

How to change this graph so that B, E and W appear according to a specific palette (say: scale_colour_brewer) with a width of .5, while R appears in scale_colour_brewer(type = "qual", palette = 7) with a width of 1?

like image 711
Lucien S. Avatar asked Feb 11 '23 21:02

Lucien S.


1 Answers

You can call subsets of your data in seperate geom_line's:

ggplot() +
  geom_line(data=dataM[dataM$variable!="R",], aes(x=bins, y=value, colour=variable), size = .5, alpha = .9) +
  geom_line(data=dataM[dataM$variable=="R",], aes(x=bins, y=value, colour=variable), size = 1.5, alpha = .9) +
  scale_colour_brewer(type = "qual", palette = 7) +
  theme_bw() +
  theme(plot.background = element_blank(), panel.grid.minor = element_blank(), axis.line = element_blank(),
        legend.key = element_blank(), legend.title = element_blank()) +
  scale_y_continuous("freq", expand=c(0,0)) + 
  scale_x_continuous("bins", expand=c(0,0))

this gives: enter image description here


Another solution (as suggested by @baptiste) is setting the size and colour scales manually:

ggplot(data=dataM, aes(x=bins, y=value, colour=variable, size = variable)) +
  geom_line(alpha = .9) +
  scale_colour_manual(breaks=c("B","E","W","R"), values=c("green","orange","blue","pink")) +
  scale_size_manual(breaks=c("B","E","W","R"), values=c(0.5,0.5,0.5,1.5)) +
  theme_bw() +
  theme(plot.background = element_blank(), panel.grid.minor = element_blank(), axis.line = element_blank(),
        legend.key = element_blank(), legend.title = element_blank()) +
  scale_y_continuous("freq", expand=c(0,0)) + 
  scale_x_continuous("bins", expand=c(0,0))

this gives more or less the same result: enter image description here

like image 70
Jaap Avatar answered Feb 14 '23 11:02

Jaap