Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create side-by-side bar charts (for multiple series) with ggplot?

Tags:

r

ggplot2

I have two sets of data (3 columns: x=categorical, y = numerical, l = location) and I would like to create a bar chart with the categories on the x axis and, for each value of the category, two vertical bars, coloured differently, with the y values for each location. By the default, Excel/OpenOffice produce this kind of chart.

I tried

qplot (x,y,data=mydata,col=location, geom="histogram")

but it produces stacked bars, not side by side. I then looked in the ggplot2 documentation and didn't find any other geom I could use (see below for full list).

Is this not possible with ggplot2?

Thanks in advance.

Name Description
abline - Line, specified by slope and intercept
area - Area plots
bar - Bars, rectangles with bases on y-axis
blank - Blank, draws nothing
boxplot - Box-and-whisker plot
contour - Display contours of a 3d surface in 2d
crossbar - Hollow bar with middle indicated by horizontal line
density - Display a smooth density estimate
density_2d - Contours from a 2d density estimate
errorbar - Error bars
histogram - Histogram
hline - Line, horizontal
interval - Base for all interval (range) geoms
jitter - Points, jittered to reduce overplotting
line - Connect observations, in order of x value
linerange - An interval represented by a vertical line
path - Connect observations, in original order
point - Points, as for a scatterplot
pointrange - An interval represented by a vertical line, with a point
in the middle
polygon - Polygon, a filled path
quantile - Add quantile lines from a quantile regression
ribbon - Ribbons, y range with continuous x values
rug - Marginal rug plots
segment - Single line segments
smooth - Add a smoothed condition mean
step - Connect observations by stairs
text - Textual annotations
tile - Tile plot as densely as possible, assuming that every tile is the same size
vline - Line, vertical
like image 541
wishihadabettername Avatar asked Oct 14 '22 00:10

wishihadabettername


1 Answers

There is a position argument that defaults to stack here. Use:

qplot (x,y,data=mydata,col=location, geom="bar", position="dodge") 

It is in the manual, just search for "dodge". Also, you probably want a "bar" geom if the y values give the height of the bar.

like image 72
Aniko Avatar answered Oct 19 '22 03:10

Aniko