Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot: Two histograms (based on two different column) in one graph

Tags:

r

ggplot2

I want to put two histograms together in one graph, but each of the histogram is based on different column. Currently I can do it like this, But the position=dodge does not work here. And there is no legend (different color for different column).

p <- ggplot(data = temp2.11)
p <- p+ geom_histogram(aes(x = diff84, y=(..count..)/sum(..count..)), 
                       alpha=0.3, fill ="red",binwidth=2,position="dodge")
p <- p+ geom_histogram(aes(x = diff08, y=(..count..)/sum(..count..)), 
                       alpha=0.3,, fill ="green",binwidth=2,position="dodge")
like image 338
ToToRo Avatar asked Aug 14 '14 19:08

ToToRo


People also ask

How do I plot multiple histograms on the same graph in R?

To create multiple histograms in ggplot2, we use ggplot() function and geom_histogram() function of the ggplot2 package. To visualize multiple groups separately we use the fill property of aesthetics function to color the plot by a categorical variable.

How do you make a histogram with two columns in R?

In this method, to create a histogram of two variables, the user has to first install and import the ggplot2 package, and then call the geom_histrogram with the specified parameters as per the requirements and needs to create the dataframe with the variable to which we need the histogram in the R programming language.


1 Answers

You have to format your table in long format, then use a long variable as aesthetics in ggplot. Using the iris data set as example...

data(iris)

# your method
library(ggplot2)
ggplot(data = iris) +
  geom_histogram(aes(x = Sepal.Length, y=(..count..)/sum(..count..)), 
                       alpha=0.3, fill ="red",binwidth=2,position="dodge") +
  geom_histogram(aes(x = Sepal.Width, y=(..count..)/sum(..count..)), 
                       alpha=0.3,, fill ="green",binwidth=2,position="dodge")

# long-format method
library(reshape2)
iris2 = melt(iris[,1:2])
ggplot(data = iris2) +
  geom_histogram(aes(x = value, y=(..count..)/sum(..count..), fill=variable), 
                 alpha=0.3, binwidth=2, position="identity")
like image 193
essicolo Avatar answered Nov 03 '22 06:11

essicolo