Adding labels to each individual plot with facet_grid - r

I am attempting to add labels (capital letters) to each plot in the following facet_grid:
p <- ggplot(mpg, aes(displ, cty)) + geom_point()
p + facet_grid(drv ~ cyl)
This outputs:
What I would like to have is this:
The major issues I am having is 1) My Y axis is scaled freely, so inputting specific coordinates for each isn't working. 2) I am not sure what keywords I should be searching here, I am sure there is a way to do this in facet_grid but I am unable to find it.

How about this? Fixing the position of label as the upper-left corner of each plot panel:
p + facet_grid(drv ~ cyl)+ annotate('text', label = LETTERS[1:12], x=min(mpg$displ), y=max(mpg$cty))
You can replace label =c('aaa','bb','fff'....), anything you like, but has to be the same number of your facet plots.
You can also fine-tune the position of the label proportional to both axis by using:
x=mean(mpg$displ)*0.6, y=max(mpg$cty)*0.97

Related

ggplot2 in R: fill underneath a geom_smooth line

I am trying to fill in a portion of a plot underneath a geom_smooth() line.
Example:
In the example the data fits on that curve. My data is not as smooth. I want to use geom_point() and a mix of geom_smooth() and geom_area() to fill in the area under the smoothed line while leaving the points above.
A picture of my data with a geom_smooth():
In other words, I want everything underneath that line to be filled in, like in Image 1.
Use predict with the type of smoothing being used. geom_smooth uses loess for n < 1000 and gam for n > 1000.
library(ggplot2)
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth() +
geom_ribbon(aes(ymin = 0,ymax = predict(loess(hwy ~ displ))),
alpha = 0.3,fill = 'green')
Which gives:

How to change style settings in stacked barchart overlaid with density line (ggplot2)

I am trying to change the style settings of this kind of chart and hope you can help me.
R code:
set_theme(theme_bw)
cglac$pred2<-as.factor(cglac$pred)
ggplot(cglac, aes(x=depth, colour=pred2))
+ geom_bar(aes(y=..density..),binwidth=3, alpha=.5, position="stack")
+ geom_density(alpha=.2)
+ xlab("Depth (m)")
+ ylab("Counts & Density")
+ coord_flip()
+ scale_x_reverse()
+ theme_bw()
which produces this graph:
Here some points:
What I want is to have the density line as black and white lines separated by symbols rather than colour (dashed line, dotted line etc).
The other thing is the histogram itself. How do I get rid of the grey background in the bars?
Can I change the bars also to black and white symbol lines (shaded etc)? So that they would match the density lines?
Last but not least I want to add a second x or in this case y axis, because of flip_coord(). The one I see right now is for the density. The other one I need would then be the count data from the pred2 variable.
Thanks for helping.
Best,
Moritz
Have different line types: inside aes(), put linetype = pred2. To make the line color black, inside geom_density, add an argument color = "black".
The "background" of the bars is called "fill". Inside geom_bar, you can set fill = NA for no fill. A more common approach is to fill in the bars with the colors, inside aes() specify fill = pred2. You might consider faceting by your variable, + facet_wrap(~ pred2, nrow = 1) might look very nice.
Shaded bars in ggplot? No, you can't do that easily. See the answers to this question for other options and hacks.
Second y-axis, similar to the shaded symbol lines, the ggplot creator thinks a second y-axis is a terrible design choice, so you can't do it at all easily. Here's a related question, including Hadley's point of view:
I believe plots with separate y scales (not y-scales that are transformations of each other) are fundamentally flawed.
It's definitely worth considering his point of view, and asking yourself if those design choices are really what you want.
Different linetypes for densities
Here's my built-in data version of what you're trying to do:
ggplot(mtcars, aes(x = hp,
linetype = cyl,
group = cyl,
color = cyl)) +
geom_histogram(aes(y=..density.., fill = cyl),
alpha=.5, position="stack") +
geom_density(color = "black") +
coord_flip() +
theme_bw()
And what I think you should do instead. This version uses facets instead of stacking/colors/linetypes. You seem to be aiming for black and white, which isn't a problem at all in this version.
ggplot(mtcars, aes(x = hp,
group = cyl)) +
geom_histogram(aes(y=..density..),
alpha=.5) +
geom_density() +
facet_wrap(~ cyl, nrow = 1) +
coord_flip() +
theme_bw()

ggplot2: How to summarize count? stat_summary or stat_bin

I'm using ggplot2 to just count and summarize the number of occurrences of each mode in my data frame. testdata$V5 is a factor with 4 different modes. Every line in testdata has an entry for mode and I want to count them.
p <- ggplot(testdata,aes(V5))
p = p + geom_histogram()
show(p)
This code produces the following plot:
I am now trying to show text labels on top of each bar plot that show the count but I can't quite understand how to achieve that using stat_summary. How can I produce a text label at the top of each x value bar showing the count?
I tried
p <- ggplot(testdata,aes(V5))
p = p + geom_histogram()
p = p + stat_summary(fun.data=count, geom="text", size=20, color="red") #<-- no effect
show(p)
but it doesn't draw anything.
You can use a "hidden" variable ..count.. in conjunction with geom_text:
p +
geom_histogram() +
stat_bin(aes(label=..count..), geom="text", position="identity", size=20, color="red")
geom_text also has hjust and vjust parameters that may be helpful.

How can I move facet labels to top of my graph?

I can create a faceted plot like so, with 3 plots stacked vertically:
ggplot(iris, aes(Petal.Length)) + stat_bin() + facet_grid(Species ~ .)
Is it possible to move the labels to the top of each graph, like they would be if I'd done horizontal stacking with facet_grid(. ~ Species)?
The reason I want this is that my plots are long time series plots, so I want the full width for each one, but the labels (which essentially function as titles to explain the facets) for each plot are too long to fit in the small label area at the right of the plot.
Yes. Use facet_wrap instead of facet_grid and be sure to also specify the argument ncol=1:
ggplot(iris, aes(Petal.Length)) + stat_bin() + facet_wrap(~Species, ncol=1)
Try this:
ggplot(iris, aes(Petal.Length)) + stat_bin() + facet_wrap(~Species,nrow = 3)

add a secondary y axis to ggplot2 plots - make it perfect

Adding a secondary y axis, scaled one of the original y axis. This topic is not new. It has been touched times, for example on this ggplot2 google groups thread. Following Hadley's advice, I tried to add the secondary y axis by geom_vline, geom_segment, and geom_text. But, it is still ugly.
So I would ask for your help on making it perfect. I think many ggplot2 users would be interested in this topic and prefer any your expertise or contributions. Thanks in advance.
#########################################
# what I have gotten.
library(ggplot2)
# build up a box plot
p <- ggplot(mtcars, aes(factor(cyl), mpg))
# add the secondary y axis on right side of the plot
p + geom_boxplot() + geom_vline(xintercept = 3.5) +
geom_segment(aes(x=3.49, y=c(7,14,21,28), xend = 3.52, yend = c(7,14,21,28))) +
geom_text(aes(x=3.55, y=c(7,14,21,28), label=c(7,14,21,28)))
To avoid hacking, you might use facet_grid instead. Depending on your data, you can customize it pretty well, to make it into more general secondary axis.
library(ggplot2)
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_boxplot() +
facet_grid(cyl ~., scales = "free")

Resources