Tara Sutjarittham
Tara Sutjarittham

Reputation: 376

multiple distribution plots (different variables) as facets in the same plot

I want to put distribution plots of different variables into a single image file. Every distribution plot (subplot) contain similar groups separated by colors.

Currently I'm using plotting each variable separately using ggplot. Then I use grid.arrange to combine all the subplots together I can represent all the distribtution.

(Example code below)

#plot1
plot_min_RTT <- ggplot(house_total_year, aes(x=min_RTT,  colour = ISP)) +
geom_density(adjust = 1/2,alpha=0.1, size = 2) 

#plot2
plot_MaxMSS <- ggplot(house_total_year, aes(x=MaxMSS,  colour = ISP)) +
geom_density(adjust = 1/2,alpha=0.1, size = 2) 

#plot3
plot_send_buffer_size <- ggplot(house_total_year, aes(x=send_buffer_size,  colour = ISP)) +
geom_density(adjust = 1/2,alpha=0.1, size = 2) 

#plot4
plot_maxSpeed <- ggplot(house_total_year_filtered, aes(x=download_speed_max_month,  colour = ISP)) +
geom_density(adjust = 1/2,alpha=0.1, size = 2) 

#combine
grid.arrange(plot_min_RTT,plot_MaxMSS,plot_send_buffer_size,plot_maxSpeed)

As can be seen, the variables used for x-axis of each subplot is different. But all has the similar grouped variables (ISP). I ended up with a single plot below:

What I currently have

However, what I actually want is to have only a single legend (ISP) for all subplots. I was thinking of using facet_wrap function from ggplot but I'm still struggling with that. Please help.

Any suggestion would be appreciated !

Thanks! :)

Upvotes: 1

Views: 4644

Answers (1)

Roman
Roman

Reputation: 17648

You provided no reproducible data, therefore I used the data.frame mpg that comes along with the ggplot package.

# Subset the data
d <- mpg[, c(1, 3:5)]
# your ISP == manufacturer
# Than transform the data to long format as stated already in the comments using reshape function melt
library(reshape2)
d_long <- melt(d)
head(d_long)
  manufacturer variable value
1         audi    displ   1.8
2         audi    displ   1.8
3         audi    displ   2.0
4         audi    displ   2.0
5         audi    displ   2.8
6         audi    displ   2.8

# Now plot the data using the variable column in facet_grid for the layout.
# scales = "free_x" is used for vairable dependend x-axis scales. 
ggplot(d_long, aes(x = value, colour = manufacturer)) + 
  geom_density() + 
  facet_grid( ~ variable, scales = "free_x") + 
  theme_bw()

Out:

enter image description here

# Instead of using facet_grid you can try 
# facet_wrap( ~ variable, scales = "free_x", ncol = 2) 
# to arrange the plots row- and colwise as your needs are. The scaling of both axis can also changed. 
ggplot(d_long, aes(x = value, colour = manufacturer)) + 
  geom_density() + 
  facet_wrap( ~ variable, scales = "free", ncol = 2) + 
  theme_bw()

Out:

enter image description here

Upvotes: 3

Related Questions