Create vertical layers in ggplot - r

For each level of the y-axis I want to separate the lines vertically by a small distance so they aren't overlapping. Can someone help me achieve this please? Also, I don't want it to be random by a method such as jittering. The placement needs to be constant across all levels.
data(mtcars)
str(mtcars)
mtcars$cyl = as.factor(mtcars$cyl)
mtcars$carb = as.factor(mtcars$carb)
ggplot(mtcars) + aes(mpg,cyl,color = carb) + geom_line() +
geom_point()

You can make use of position_dodge, though because that only has an option to set width, I believe that you will have to construct it with the opposite axes, then use coord_flip to get it back the way you wanted it:
ggplot(mtcars
, aes(cyl, mpg
,color = carb) ) +
geom_line(position = position_dodge(0.3)) +
geom_point(position = position_dodge(0.3)) +
coord_flip()
Gives:

Related

Coloring subset of lines in a plot using ggplot

I am trying to connect the dots on my plot using geom_path(). I also want to color certain lines(intervals) based on a group variable(t). This is what I have so far:
ggplot(data, aes(x=x, y=x)) +
geom_point() +
geom_path(color=t)
What this does is it "incorrectly" connects the points based on this group. I just want the correct connecting lines to have a separate color.
Could any one help me with this?
Since you did not share your data: You could be experiencing an edge case that occurs if you color by boolean; e.g., a specific value of a variable.
In this case, ggplot groups your geom_path by var == x. You can prevent this by adding group = 1.
Basic (somewhat contrived) example
ggplot(mtcars) +
geom_point(aes(mpg, hp)) +
geom_path(aes(mpg, hp))
Above plot with color = cyl == 4
ggplot(mtcars) +
geom_point(aes(mpg, hp)) +
geom_path(aes(mpg, hp, color = cyl == 4))
Above plot with group = 1
ggplot(mtcars) +
geom_point(aes(mpg, hp)) +
geom_path(aes(mpg, hp, color = cyl == 4, group = 1))
If you pass either a single color (not what you want), or a vector of colors equal to the number of plot elements, you can get ggplot to color the lines for you. So, for instance,
data <- data.frame(x = 1:10, y = 1:10)
ggplot(data, aes(x=x, y=x)) +
geom_point() +
geom_path(color=rainbow(10))

geom_dotplot() loses dodge after applying colour aesthetics

I want to organize my data by one category on the X-axis, but color it by another category as in this example:
Graph 1, without coloring:
require(ggplot2)
nocolor <- ggplot(mtcars, aes(x=as.factor(cyl), y=disp)) +
geom_dotplot(binaxis="y", stackdir = "center")
print(nocolor)
Graph 2, with coloring:
nododge <- ggplot(mtcars, aes(x=as.factor(cyl), y=disp, fill=as.factor(gear))) +
geom_dotplot(binaxis="y", stackdir = "center")
print(nododge)
One problem that occurs after introducing coloring is that the dots belonging to different groups wont dodge one another anymore. This causes problems with my real data, as I get dots that happen to have the same value and completely obscure one another.
Then I tried this, but it garbled my data:
Graph 3:
garbled <- ggplot(mtcars, aes(x=as.factor(cyl), y=disp)) +
geom_dotplot(binaxis="y", stackdir = "center", fill=as.factor(mtcars$gear))
print(garbled)
The dots dodge one another, but the the coloring is just random and is not true to the actual data.
I expected the answer to this question to solve my problem, but the coloring remained random:
Graph 4:
graphdata <- mtcars
graphdata$colorname <- as.factor(graphdata$gear)
levels(graphdata$colorname) <- c("red", "blue", "black")
jalapic <- ggplot(graphdata, aes(x=as.factor(cyl), y=disp)) +
geom_dotplot(binaxis="y", stackdir = "center", fill=as.character(graphdata$colorname))
print(jalapic)
Does anyone have an idea how to get the dots in Graph #2 to dodge one another, or how to fix the coloring in graphs 3 or 4? I would really appreciate any help, thanks.
Using binpositions = "all" and stackgroups = TRUE:
ggplot(mtcars, aes(x=as.factor(cyl), y=disp, fill=as.factor(gear))) +
geom_dotplot(binaxis="y", stackdir = "center", binpositions="all", stackgroups=TRUE)
gives:
A possible alternative is using stackdir = "up":
ggplot(mtcars, aes(x=as.factor(cyl), y=disp, fill=as.factor(gear))) +
geom_dotplot(binaxis="y", stackdir = "up", binpositions="all", stackgroups=TRUE)
which gives:
Here's another option that might work better than a dotplot, depending on your needs. We plot the individual points, but we separate them so that each point is visible.
In my original answer, I used position_jitterdodge, but the randomness of that method resulted in overlapping points and little control over point placement. Below is an updated approach that directly controls point placement to prevent overlap.
In the example below, we have cyl as the x variable, disp as the y variable, and gear as the colour aesthetic.
Within each cyl, we want points to be dodged by gear.
Within each gear we want points with similar values of disp to be separated horizontally so that they don't overlap.
We do this by adding appropriate increments to the value of cyl in order to shift the horizontal placement of the points. We control this with two parameters: dodge separates groups of points by gear, while sep controls the separation of points within each gear that have similar values of disp. We determine "similar values of disp" by creating a grouping variable called dispGrp, which is just disp rounded to the nearest ten (although this can, of course, be adjusted, depending on the scale of the data, size of the plotted points, and physical size of the graph).
To determine the x-value of each point, we start with the value of cyl, add dodging by gear, and finally spread the points within each gear and dispGrp combination by amounts that depend on the number of points within the each grouping.
All of these data transformations are done within a dplyr chain, and the resulting data frame is then fed to ggplot. The sequence of data transformations and plotting could be generalized into a function, but the code below addressed only the specific case in the question.
library(dplyr)
library(ggplot2)
dodge = 0.3 # Controls the amount dodging
sep = 0.05 # Within each dodge group, controls the amount of point separation
mtcars %>%
# Round disp to nearest 10 to identify groups of points that need to be separated
mutate(dispGrp = round(disp, -1)) %>%
group_by(gear, cyl, dispGrp) %>%
arrange(disp) %>%
# Within each cyl, dodge by gear, then, within each gear, separate points
# within each dispGrp
mutate(cylDodge = cyl + dodge*(gear - mean(unique(mtcars$gear))) +
sep*seq(-(n()-1), n()-1, length.out=n())) %>%
ggplot(aes(x=cylDodge, y=disp, fill=as.factor(gear))) +
geom_point(pch=21, size=2) +
theme_bw() +
scale_x_continuous(breaks=sort(unique(mtcars$cyl)))
Here's my original answer, using position_jitterdodge to dodge by color and then jitter within each color group to separate overlapping points:
set.seed(3521)
ggplot(mtcars, aes(x=factor(cyl), y=disp, fill=as.factor(gear))) +
geom_point(pch=21, size=1.5, position=position_jitterdodge(jitter.width=1.2, dodge.width=1)) +
theme_bw()

geom_point plot with only number without circles

In ggplot in R, is it possible to plot each point with a unique number but without circles surrounded? I tried to use color "white" but it doesn't work.
I would recommend geom_text.
set.seed(101)
dd <- data.frame(x=rnorm(50),y=rnorm(50),id=1:50)
library(ggplot2)
ggplot(dd,aes(x,y))+geom_text(aes(label=id))
I'll show how to do it with geom_text and/or geom_point.
Using geom_text (recommended)
For this example I'll use the built-in dataset mtcars and let's pretend the numbers you want to display are the weights (wt) variable:
data(mtcars)
p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars)))
p + geom_text(aes(label = wt),
parse = TRUE)
or if you want an example with truly unique numbers, we can just make up an index using seq:
data(mtcars)
p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars)))
p + geom_text(aes(label = seq(1:32)),
parse = TRUE)
Using geom_point
While it would require more work, it actually is possible to do this with geom_point.
This is a reference image of some of the shapes you can use with geom_point:
As you can see, shapes 48 to 57 are 0 to 9. You can leverage these shapes (and combinations of them to form an infinite amount of numbers) via geom_point like this:
d=data.frame(p=c(48:57))
ggplot() +
scale_y_continuous(name="") +
scale_x_continuous(name="") +
scale_shape_identity() +
geom_point(data=d, mapping=aes(x=p%%16, y=p%/%16, shape=p), size=5, fill="red")
Finally, a trivial example using mtcars + geom_point with arbitrary numbers:
d=data.frame(p=c(48:57,48:57,48:57,48,49))
attach(mtcars)
ggplot(mtcars) +
scale_y_continuous(name="") +
scale_x_continuous(name="") +
scale_shape_identity() +
geom_point(data=d, mapping=aes(x=wt, y=mpg, shape=p), size=5, fill="red")

How to use free scales but keep a fixed reference point in ggplot?

I am trying to create a plot with facets. Each facet should have its own scale, but for ease of visualization I would like each facet to show a fixed y point. Is this possible with ggplot?
This is an example using the mtcars dataset. I plot the weight (wg) as a function of the number of miles per gallon (mpg). The facets represent the number of cylinders of each car. As you can see, I would like the y scales to vary across facets, but still have a reference point (3, in the example) at the same height across facets. Any suggestions?
library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(mpg, wt)) + geom_point() +
geom_hline (yintercept=3, colour="red", lty=6, lwd=1) +
facet_wrap( ~ cyl, scales = "free_y")
[EDIT: in my actual data, the fixed reference point should be at y = 0. I used y = 3 in the example above because 0 didn't make sense for the range of the data points in the example]
It's unclear where the line should be, let's assume in the middle; you could compute limits outside ggplot, and add a dummy layer to set the scales,
library(ggplot2)
library(plyr)
# data frame where 3 is the middle
# 3 = (min + max) /2
dummy <- ddply(mtcars, "cyl", summarise,
min = 6 - max(wt),
max = 6 - min(wt))
ggplot(mtcars, aes(mpg, wt)) + geom_point() +
geom_blank(data=dummy, aes(y=min, x=Inf)) +
geom_blank(data=dummy, aes(y=max, x=Inf)) +
geom_hline (yintercept=3, colour="red", lty=6, lwd=1) +
facet_wrap( ~ cyl, scales = "free_y")

How would you plot a box plot and specific points on the same plot?

We can draw box plot as below:
qplot(factor(cyl), mpg, data = mtcars, geom = "boxplot")
and point as:
qplot(factor(cyl), mpg, data = mtcars, geom = "point")
How would you combine both - but just to show a few specific points(say when wt is less than 2) on top of the box?
If you are trying to plot two geoms with two different datasets (boxplot for mtcars, points for a data.frame of literal values), this is a way to do it that makes your intent clear. This works with the current (Sep 2016) version of ggplot (ggplot2_2.1.0)
library(ggplot2)
ggplot() +
# box plot of mtcars (mpg vs cyl)
geom_boxplot(data = mtcars,
aes(x = factor(cyl), y= mpg)) +
# points of data.frame literal
geom_point(data = data.frame(x = factor(c(4,6,8)), y = c(15,20,25)),
aes(x=x, y=y),
color = 'red')
I threw in a color = 'red' for the set of points, so it's easy to distinguish them from the points generated as part of geom_boxplot
Use + geom_point(...) on your qplot (just add a + geom_point() to get all the points plotted).
To plot selectively just select those points that you want to plot:
n <- nrow(mtcars)
# plot every second point
idx <- seq(1,n,by=2)
qplot( factor(cyl), mpg, data=mtcars, geom="boxplot" ) +
geom_point( aes(x=factor(cyl)[idx],y=mpg[idx]) ) # <-- see [idx] ?
If you know the points before-hand, you can feed them in directly e.g.:
qplot( factor(cyl), mpg, data=mtcars, geom="boxplot" ) +
geom_point( aes(x=factor(c(4,6,8)),y=c(15,20,25)) ) # plot (4,15),(6,20),...
You can show both by using ggplot() rather than qplot(). The syntax may be a little harder to understand, but you can usually get much more done. If you want to plot both the box plot and the points you can write:
boxpt <- ggplot(data = mtcars, aes(factor(cyl), mpg))
boxpt + geom_boxplot(aes(factor(cyl), mpg)) + geom_point(aes(factor(cyl), mpg))
I don't know what you mean by only plotting specific points on top of the box, but if you want a cheap (and probably not very smart) way of just showing points above the edge of the box, here it is:
boxpt + geom_boxplot(aes(factor(cyl), mpg)) + geom_point(data = ddply(mtcars, .(cyl),summarise, mpg = mpg[mpg > quantile(mpg, 0.75)]), aes(factor(cyl), mpg))
Basically it's the same thing except for the data supplied to geom_point is adjusted to include only the mpg numbers in the top quarter of the distribution by cylinder. In general I'm not sure this is good practice because I think people expect to see points beyond the whiskers only, but there you go.

Resources