Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot multiple columns in R for the same X-Axis Value [duplicate]

Tags:

plot

r

ggplot2

I need to plot three values, to make three bars for each value of the X-Axis. My data is: My dataframe DF

In the X-Axis must be the column labeled as "m" and for each "m" value I need to plot the correspondent "x","y" and "z" value.

I want to use ggplot2 and I need something like this:

Goal

like image 446
Captain Nemo Avatar asked Apr 23 '15 17:04

Captain Nemo


People also ask

How do I plot multiple times in R?

Method 1: Using Basic R methods First, we create a data vector that has data for all the time series that have to be drawn. Then we plot the time series using the first dataset and plot() function. Then add other time series using line() function to the existing plot.

How do I show multiple columns in R?

To pick out single or multiple columns use the select() function. The select() function expects a dataframe as it's first input ('argument', in R language), followed by the names of the columns you want to extract with a comma between each name.

How do I plot multiple graphs on the same page in R?

To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.


1 Answers

I created my own dataset to demonstrate how to do it:

Data:

x <- runif(12,1,1.5)
y <- runif(12,1,1.5)
z <- runif(12,1,1.5)
m <- letters[1:12]
df <- data.frame(x,y,z,m)

Solution:

#first of all you need to melt your data.frame
library(reshape2)
#when you melt essentially you create only one column with the value
#and one column with the variable i.e. your x,y,z 
df <- melt(df, id.vars='m')

#ggplot it. x axis will be m, y will be the value and fill will be
#essentially your x,y,z
library(ggplot2)
ggplot(df, aes(x=m, y=value, fill=variable)) + geom_bar(stat='identity')

Output:

enter image description here

If you want the bars one next to the other you need to specify the dodge position at geom_bar i.e.:

ggplot(df, aes(x=m, y=value, fill=variable)) + 
       geom_bar(stat='identity', position='dodge')

enter image description here

like image 66
LyzandeR Avatar answered Oct 21 '22 11:10

LyzandeR