Increase the space between x axis labels ggplot? - r

Here is my ggplot and I need to adjust the spacing between x axis labels and make the plot larger. Please advise what is missing here? Trying to play with expand but without any luck:
ggplot(device_contacts_jaccard_android_ios, aes(x = factor(uuid_lev), y = j, fill = factor(android))) +
geom_boxplot() +
facet_wrap( ~ dt) +
scale_x_discrete(expand=c(0, 0.5)) +
theme(axis.text.x = element_text(angle = -90, hjust = 0))
I have checked other answers here, no one solved my issue, correct me if I am wrong.

Use ggsave or pdf(...);...; dev.off() to increase the output size of the image. Once you do that, the space between axis text labels should increase. You could also decrease the font using element_text(size = 7), for example.
Note that in ggsave(..., size, width) are in inches, by default. Good starting points are width = 8 and height = 8. If you want to change the units, try ggsave(..., units = "cm").

Related

Bounding position for geom_text()

I am making several instances of a tilted bar chart. As the sizes of count and the differences in percent vary, part of one of the labels (count) is pushed outside the bar in some instances. I need the labels to be entirely inside the bar in all instances. If not repositioned to fit inside the bar, I need the labels to be centered as is.
The code is:
library(tidyverse)
library(ggplot2)
data <- tibble(type = c('Cat', 'Dog'),
group = c('Pets', 'Pets'),
count = c(10000, 990000),
percent = c(1, 99))
ggplot(data, aes(x = group, y = percent, fill = type)) +
geom_bar(stat = 'identity',
position = position_stack(reverse = TRUE)) +
coord_flip() +
geom_text(aes(label = count),
position = position_stack(vjust = 0.5,
reverse = TRUE))
Use hjust="inward":
ggplot(data, aes(x = group, y = percent, fill = type)) +
geom_bar(stat = 'identity', position = position_stack(reverse = TRUE)) +
coord_flip() +
geom_text(aes(label = count), hjust = "inward", position = position_stack(vjust = 0.5, reverse = TRUE))
One thing key to note here is that plots in ggplot are drawn differently depending on the graphics device resolution, width, and height settings. This is why plots look a bit different depending on the computer you use to plot them. If I take your default graph and save different aspect ratios, this becomes evident:
width=3, height=5
width=7, height=5
The aspect ratio and resolution change the plot. You can also see this for yourself within R studio by just resizing the plot viewer window.
With that being said, there are some options to adjust your plot to be less likely to clip text out of bounds:
Rotate your text or rotate your plot back to horizontal bars. For long text labels, they are going to work out better with horizontal bars anyway.
geom_text_repel from the ggrepel package. Direct replacement of geom_text puts your labels in the plot area, and you can use min.segment.length= to specify the minimum line length as well as force= and direction= to play with positioning. Again, works better if you flip back your chart.
Use the expand= argument applied to scale_y_continuous. Try adding scale_y_continuous(expand=c(0.25,0.25)) to your plot, for example. Note that since your coordinate system is flipped, you have to specify "y" to expand "x". This expands the plot area around the geoms.
Change the output width= and height= and resolution when exporting your plots. As indicated above, this is the simple solution.
There are probably other suggestions, but that's mine.

Reduce space between groups of bars in ggplot2

I haven't been able to remove extra white space flanking groups of bars in geom_plot.
I'd like to do what Roland achieves here: Remove space between bars ggplot2 but when I try to implement his solution I get the error "Warning message:
geom_bar() no longer has a binwidth parameter. Please use geom_histogram() instead."
I added this line of code to my plot (trying different widths):
geom_histogram(binwidth = 0.5) +
which returns "Error: stat_bin() must not be used with a y aesthetic." and no plot.
Data:
mydf<- data.frame(Treatment = c("Con", "Con", "Ex", "Ex"),
Response = rep(c("Alive", "Dead"), times=2),
Count = c(259,10,290,21))
aPalette<-c("#009E73", "#D55E00")
Plot:
example<-ggplot(mydf, aes(factor(Response), Count, fill = Treatment)) +
geom_bar(stat="identity",position = position_dodge(width = 0.55), width =
0.5) +
scale_fill_manual(values = aPalette, name = "Treatment") + #legend title
theme_classic() +
labs(x = "Response",
y = "Count") +
scale_y_continuous(breaks = c(0,50,100,150,200,250,275), expand = c(0,0),
limits = c(0, 260)) +
theme(legend.position = c(0.7, 0.3)) +
theme(text = element_text(size = 15)) #change all text size
example
Returns:
Note: I don't know why I'm getting "Warning message: Removed 1 rows containing missing values (geom_bar)." but I'm not concerned about it because that doesn't happen using my actual data
**Edit re: note - this is happening because I set the limit for the y-axis lower then the max value for the bar that was removed. I'm not going to change to code so I don't have to redraw my figure, but changing
limits = c(0, 260)
to
limits = c(0, 300)
will show all the bars. In case someone else had a similar problem. I'm going to find a post related to this issue and will make this edit more concise when I can link an answer
Forgive me if I completely missed what your trying to accomplish here but the only reason that ggplot has included so much white space is because you constrained the bars to a particular width and increased the size of the graph.
The white space within the graph is an output of width of the bars and width of the graph.
Using your original graph...
We notice a lot of whitespace but you both made the bins small and your graph wide. Think of the space as a compromise between bins and whitespace. Its illogical to expect a wide graph with small bins and no whitespace. To fix this we can either decrease the graph size or increase the bin size.
First we increase the bin size back to normal by removing your constraints.
Which looks rediculous....
But by looking at the Remove space between bars ggplot2 link that you included above all he did was remove constraints and limit width. Doing so would result in a similar graph...
Including the graph from your link above....
And removing all of your constraints....
example<-ggplot(mydf, aes(factor(Response), Count, fill = Treatment)) +
geom_bar(stat="identity",position = position_dodge()) +
scale_fill_manual(values = aPalette, name = "Treatment") +
theme_bw() +
labs(x = "Response", y = "Count")
example
If your goal was not to make your graph similar to the one in the link by removing whitespace let me know, other then that I hope this helped.

ggplot2: log10-scale and axis limits

Basically like this question:
How can I set axis ranges in ggplot2 when using a log scale?
The issue I have with the solution and ggplot2 it seems that it overdraws. I want limits = c(1,1e8) I do not want the tiny bit additional space below and above this limits. See below:
I want the limits to be at the edge of the graph and 0 additional space. How do I achieve that?
Try:
+ scale_y_log10(limits = c(1, 1e8), expand = c(0, 0))
although personally, I think the extra spacing serves a purpose.
ggplot(data = df,aes(x = x, y =y)) +
geom_point() +
scale_y_log10(limits = c(1,1e8), expand = c(0, 0))

Vertical alignment of ggplots without using grids

I have a large number of plots computed with ggplot, however when the y-axis has different number of digits, the left side of the plot are not aligned. They will not be inserted directly under / over each other, so a grid cannot be used. Nevertheless, I would like them to have the exact same size. How could this be achieved?
qplot(rnorm(10),1:10, colour = runif(10))
qplot(rnorm(10),1001:1010, colour = runif(10))
You can manually adjust the y-axis labels to match lengths or just rotate everything 90 degrees. Although there might be better solution out there.
ggplot(data.frame(x=rnorm(10),y=1:10),aes(x,y, colour = x))+geom_point()+
scale_y_continuous(breaks = seq(0,10,by=2),labels=c('0.000','2.000','4.000','6.000','8.000','10.000'))
ggplot(data.frame(x=rnorm(10),y=1001:1010),aes(x,y,colour = x) )+geom_point()+
theme(axis.text.y = element_text(angle = 90))
So would you like to have a fixed y-axis limits? you can use the coord_cartesian()
qplot(rnorm(10),1:10, colour = runif(10)) +
coord_cartesian(ylim = c(min(y_var), max(y_var)))
This shall fix the y-axis limits for all plots. Here y_var refers to the y variable being used for the y-axis

How to adjust figure settings in plotmatrix?

Can I adjust the point size, alpha, font, and axis ticks in a plotmatrix?
Here is an example:
library(ggplot2)
plotmatrix(iris)
How can I:
make the points twice as big
set alpha = 0.5
have no more than 5 ticks on each axis
set font to 1/2 size?
I have fiddled with the mapping = aes() argument to plotmatrix as well as opts() and adding layers such as + geom_point(alpha = 0.5, size = 14), but none of these seem to do anything. I have hacked a bit of a fix to the size by writing to a large pdf (pdf(file = "foo.pdf", height = 10, width = 10)), but this provides only a limited amount of control.
Pretty much all of the ggplot2 scatterplot matrix options are still fairly new and can be a bit experimental.
But the facilities in GGally do allows you to construct this kind of plot manually, though:
custom_iris <- ggpairs(iris,upper = "blank",lower = "blank",
title = "Custom Example")
p1 <- ggplot(iris,aes(x = Sepal.Length,y = Sepal.Width)) +
geom_point(size = 1,alpha = 0.3)
p2 <- ggplot(iris,aes(x = Sepal.Width,y = Sepal.Length)) +
geom_point()
custom_iris <- putPlot(custom_iris,p1,2,1)
custom_iris <- putPlot(custom_iris,p2,3,2)
custom_iris
I did that simply by directly following the last example in ?ggpairs.

Resources