Questions tagged [ggplot2]
ggplot2 is an actively maintained open-source chart-drawing package for R, written by Hadley Wickham, based upon the principles of "Grammar of Graphics". It partially replaces R's basic plot and the lattice package, while providing a clean, powerful, orthogonal and fun API.
5,500
questions
310
votes
14answers
348k views
Order Bars in ggplot2 bar graph
I am trying to make a bar graph where the largest bar would be nearest to the y axis and the shortest bar would be furthest. So this is kind of like the Table I have
Name Position
1 James ...
241
votes
15answers
321k views
ggplot with 2 y axes on each side and different scales
I need to plot a bar chart showing counts and a line chart showing rate all in one chart, I can do both of them separately, but when I put them together, I scale of the first layer (i.e. the geom_bar) ...
313
votes
5answers
487k views
Plotting two variables as lines using ggplot2 on the same graph
A very newbish question, but say I have data like this:
test_data <-
data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
date = ...
14
votes
1answer
2k views
Issue when passing variable with dollar sign notation ($) to aes() in combination with facet_grid() or facet_wrap()
I am doing some analysis in ggplot2 at the moment for a project and by chance I stumbled across some (for me) weird behavior that I cannot explain. When I write aes(x = cyl, ...) the plot looks ...
236
votes
10answers
275k views
Add regression line equation and R^2 on graph
I wonder how to add regression line equation and R^2 on the ggplot. My code is:
library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = ...
138
votes
5answers
249k views
Order discrete x scale by frequency/value
I am making a dodged bar chart using ggplot with discrete x scale, the x axis are now arranged in alphabetical order, but I need to rearrange it so that it is ordered by the value of the y-axis (i.e., ...
146
votes
3answers
277k views
Add legend to ggplot2 line plot
I have a question about legends in ggplot2. I managed to plot three lines in the same graph and want to add a legend with the three colors used. This is the code used
library(ggplot2)
require(...
113
votes
2answers
183k views
Showing data values on stacked bar chart in ggplot2
I'd like to show data values on stacked bar chart in ggplot2. Here is my attempted code
Year <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category <- c(rep(c("A", "B"...
105
votes
9answers
30k views
Left align two graph edges (ggplot)
I'm using ggplot and have two graphs that I want to display on top of each other. I used grid.arrange from gridExtra to stack them. The problem is I want the left edges of the graphs to align as ...
353
votes
13answers
411k views
Side-by-side plots with ggplot2
I would like to place two plots side by side using the ggplot2 package, i.e. do the equivalent of par(mfrow=c(1,2)).
For example, I would like to have the following two plots show side-by-side with ...
64
votes
7answers
71k views
Using ggplot2, can I insert a break in the axis?
I want to make a bar plot where one of the values is much bigger than all other values. Is there a way of having a discontinuous y-axis? My data is as follows:
df <- data.frame(a = c(1,2,3,500), b ...
596
votes
16answers
1.4m views
Plot two graphs in same plot in R
I would like to plot y1 and y2 in the same plot.
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
plot(x, y1, type = "l", col = "red")
plot(x, y2, type = "l", col = "green")
But ...
114
votes
6answers
58k views
How to use a variable to specify column name in ggplot
I have a ggplot command
ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )
inside a function. But I would like to be able to use a parameter of the function to pick out the ...
179
votes
8answers
225k views
Show percent % instead of counts in charts of categorical variables
I'm plotting a categorical variable and instead of showing the counts for each category value.
I'm looking for a way to get ggplot to display the percentage of values in that category. Of course, it ...
64
votes
1answer
21k views
ggplot's qplot does not execute on sourcing
Let's assume I have 2 source files, the first one named example1.r and the second one example2.r (given below).
example1.r
plot(1:10,1:10)
example2.r
qplot(1:10,1:10)
When I source example1.r, ...
368
votes
2answers
585k views
How to set limits for axes in ggplot2 R plots?
I plot the following:
library(ggplot2)
carrots <- data.frame(length = rnorm(500000, 10000, 10000))
cukes <- data.frame(length = rnorm(50000, 10000, 20000))
carrots$veg <- 'carrot'
cukes$...
116
votes
3answers
78k views
How to remove space between axis & area-plot in ggplot2?
I have the following dataframe:
uniq <- structure(list(year = c(1986L, 1987L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 2007L, ...
70
votes
3answers
71k views
ggplot2 - annotate outside of plot
I would like to associate sample size values with points on a plot. I can use geom_text to position the numbers near the points, but this is messy. It would be much cleaner to line them up along the ...
182
votes
5answers
213k views
How to assign colors to categorical variables in ggplot2 that have stable mapping?
I've been getting up to speed with R in the last month.
Here is my question:
What is a good way to assign colors to categorical variables in ggplot2 that have stable mapping? I need consistent ...
103
votes
8answers
82k views
How to add texture to fill colors in ggplot2
I'm currently using scale_brewer() for fill and these look beautiful in color (on screen and via color printer) but print relatively uniformly as greys when using a black and white printer. I searched ...
203
votes
4answers
133k views
Emulate ggplot2 default color palette
What function can I use to emulate ggplot2's default color palette for a desired number of colors. For example, an input of 3 would produce a character vector of HEX colors with these colors:
306
votes
11answers
364k views
How to save a plot as image on the disk?
I plot a simple linear regression using R.
I would like to save that image as PNG or JPEG, is it possible to do it automatically? (via code)
There are two different questions: First, I am already ...
154
votes
6answers
84k views
Annotating text on individual facet in ggplot2
I want to annotate some text on last facet of the plot with the following code:
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p <- p + ...
85
votes
5answers
133k views
Changing fonts in ggplot2
Once upon a time, I changed my ggplot2 font using using windowsFonts(Times=windowsFont("TT Times New Roman")) to change it. Now I can't get it off of this.
In trying to set family="" in ggplot2 ...
124
votes
1answer
147k views
Reorder bars in geom_bar ggplot2 by value
I am trying to make a bar-plot where the plot is ordered from the miRNA with the highest value to the miRNA with the lowest. Why does my code not work?
> head(corr.m)
miRNA ...
127
votes
6answers
30k views
Remove 'a' from legend when using aesthetics and geom_text
How can I can remove the letter 'a' from the legend generated by this code? If I remove the geom_text, then the 'a' letter will not show in the legend. I want to keep geom_text, though.
ggplot(data = ...
42
votes
6answers
26k views
Multirow axis labels with nested grouping variables
I would like the levels of two different nested grouping variables to appear on separate lines below the plot, and not in the legend. What I have right now is this code:
data <- read.table(text = "...
38
votes
4answers
123k views
Plot multiple columns on the same graph in R [duplicate]
I have the following data frame:
A B C D Xax
0.451 0.333 0.034 0.173 0.22
0.491 0.270 0.033 0.207 0.34
0.389 0.249 0.084 0.271 0.54
0....
239
votes
20answers
247k views
How to change facet labels?
I have used the following ggplot command:
ggplot(survey, aes(x = age)) + stat_bin(aes(n = nrow(h3), y = ..count.. / n), binwidth = 10)
+ scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, ...
146
votes
3answers
126k views
Force the origin to start at 0
How can I set the origin / interception of the y-axis and x-axis in ggplot2?
The line of the x-axis should be exactly at y=Z.
With Z=0 or another given value.
76
votes
6answers
308k views
Plot multiple boxplot in one graph
I saved my data in as a .csv file with 12 columns. Columns two through 11 (labeled F1, F2, ..., F11) are features. Column one contains the label of these features either good or bad.
I would like to ...
74
votes
2answers
70k views
Combine legends for color and shape into a single legend
I'm creating a plot in ggplot from a 2 x 2 study design and would like to use 2 colors and 2 symbols to classify my 4 different treatment combinations. Currently I have 2 legends, one for the colors ...
126
votes
1answer
78k views
ggplot does not work if it is inside a for loop although it works outside of it [duplicate]
I'm using a simple ggplot function which works fine outside a loop but not inside even if the iterative value does not interfere with the ggplot function. Why is it so ?
Here is my code
x=1:7
y=1:7
...
104
votes
4answers
94k views
How to use Greek symbols in ggplot2?
My categories need to be named with Greek letters. I am using ggplot2, and it works beautifully with the data. Unfortunately I cannot figure out how to put those greek symbols on the x axis (at the ...
78
votes
2answers
158k views
How do you specifically order ggplot2 x axis instead of alphabetical order? [duplicate]
I'm trying to make a heatmap using ggplot2 using the geom_tiles function
here is my code below:
p<-ggplot(data,aes(Treatment,organisms))+geom_tile(aes(fill=S))+
scale_fill_gradient(low = "black",...
43
votes
2answers
19k views
Make the background of a graph different colours in different regions
I'm making a straightforward barchart in R using the ggplot2 package. Rather than the grey default I'd like to divide the background into five regions, each a different (but similarly understated) ...
702
votes
8answers
813k views
Rotating and spacing axis labels in ggplot2
I have a plot where the x-axis is a factor whose labels are long. While probably not an ideal visualization, for now I'd like to simply rotate these labels to be vertical. I've figured this part out ...
72
votes
4answers
20k views
Combine base and ggplot graphics in R figure window
I would like to generate a figure that has a combination of base and ggplot graphics. The following code shows my figure using the base plotting functions of R:
t <- c(1:(24*14))
P <- 24
A &...
52
votes
3answers
44k views
Multi-row x-axis labels in ggplot line chart
Edit: This question has been marked as duplicated, but the responses here have been tried and did not work because the case in question is a line chart, not a bar chart. Applying those methods ...
33
votes
1answer
5k views
Generate multiple graphics from within an R function
I'd like to spawn several graphics windows from within a function in R using ggplot graphics...
testf <- function(a, b) {
devAskNewPage(TRUE)
qplot(a, b);
# grid.newpage(recording = TRUE)
...
61
votes
7answers
42k views
Draw a circle with ggplot2
Maybe it is a silly question, but I couldn't find the answer in the handbook of ggplot2 nor with "aunt" google...
How do I plot a circle with ggplot2 as an additional layer if I have a middle point ...
67
votes
4answers
121k views
Create stacked barplot where each stack is scaled to sum to 100%
I have a data.frame like this:
df <- read.csv(text = "ONE,TWO,THREE
23,234,324
34,534,12
56,324,124
34,...
12
votes
2answers
4k views
“for” loop only adds the final ggplot layer
Summary: When I use a "for" loop to add layers to a violin plot (in ggplot), the only layer that is added is the one created by the final loop iteration. Yet in explicit code that mimics the code that ...
200
votes
5answers
255k views
Increase number of axis ticks
I'm generating plots for some data, but the number of ticks is too small, I need more precision on the reading.
Is there some way to increase the number of axis ticks in ggplot2?
I know I can tell ...
142
votes
9answers
118k views
Add a common Legend for combined ggplots
I have two ggplots which I align horizontally with grid.arrange. I have looked through a lot of forum posts, but everything I try seem to be commands that are now updated and named something else.
...
179
votes
5answers
225k views
ggplot2 line chart gives “geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?”
With this data frame ("df"):
year pollution
1 1999 346.82000
2 2002 134.30882
3 2005 130.43038
4 2008 88.27546
I try to create a line chart like this:
plot5 <- ggplot(df, aes(year, pollution))...
137
votes
14answers
59k views
Scatterplot with marginal histograms in ggplot2
Is there a way of creating scatterplots with marginal histograms just like in the sample below in ggplot2? In Matlab it is the scatterhist() function and there exist equivalents for R as well. However,...
316
votes
12answers
557k views
How to change legend title in ggplot
I have the following plot like below.
It was created with this command:
library(ggplot2)
df <- data.frame(cond = factor(rep(c("A", "B"), each = 200)),
rating = c(rnorm(200), ...
54
votes
5answers
38k views
Method to extract stat_smooth line fit
Is there a way to extract the values of the fitted line returned from stat_smooth?
The code I am using looks like this:
p <- ggplot(df1, aes(x=Days, y= Qty,group=Category,color=Category))
p <- ...
98
votes
1answer
55k views
Position geom_text on dodged barplot
I tried to make the title self-explanatory, but here goes - data first:
dtf <- structure(list(variable = structure(c(1L, 1L, 2L, 2L, 3L, 3L,
4L, 4L, 5L, 5L), .Label = c("vma", "vla", "ia", "fma", ...