How to increase the padding around a plot? - r

I have a horizontal barchart, with too-tight padding:
data <- data.frame(month = factor(c("Nov", "Dec", "Jan", "Feb")),
count = c(1489, 788, 823, 1002))
g <- (ggplot2::ggplot(data, ggplot2::aes(x=month, y=count)) +
ggplot2::geom_col() +
ggplot2::scale_x_discrete(limits=rev(data$month)) +
ggplot2::coord_flip()) +
g
I am happy with the spacing between the bars, but I want a lot more space all around the 4-bar stack. In other words, I want more padding around the central 4-bar figure. The area of the light-gray rectangle that serves as the background for the 4-bar stack should remain unchanged, but the size of the 4-bar stack within that rectangle should shrink, with the net effect of produing wider padding all around the 4-bar stack; in other words, more of the light-gray background will be visible around the 4-bar stack.
Also, I am looking for ways to do this that are entirely independent of the actual values on the axes. The code should produce the same visual effect whether the x-range is 0-1500 or 0-1500000 or altogether non-numeric (i.e. categorical).
This means that the extra padding must be specified either (a) as percentages for the figure's total width and height; or (b) fixed numbers of pixels; or (c) fixed units of measurement (cm, inches, printer points, etc.).
Lastly, ideally, I would like to be able to specify the padding for all four edges independently.
How can I do this?
IMPORTANT I don't want to increase the margins around the light gray background. I want to increase the padding within the light gray background. If this distinction is not clear, please see this.

You can use the expand_scale function within the expand argument to scale_x_continuous-type functions. It's a bit wordy, but...
ggplot(data, aes(x=month,y=count)) +
geom_bar(stat="identity") +
scale_x_discrete(limits=(data$month), expand=expand_scale(mult=c(0.5,0.5))) +
geom_text(aes(label=count), hjust=-0.3) +
coord_flip() + scale_y_continuous(expand=expand_scale(mult=c(0.5,0.5)))
Play around with the two elements of the mult vector, which define the padding above and below the axis, so you can change each side of the plot independently (although it's not exactly transparent, and will take some fiddling). See ?expand_scale for more info.

Related

Change space between bars in histogram - R

I created a histogram in RStudio with the following code:
ggplot(data_csv, aes(x=Phasenew, fill=Success)) +
geom_histogram(binwidth = 1, position = "dodge", color="white")
What I want to do now, is to add more space between the bars of the histgram. I already tried the "width" parameter, but that one obviously does not work in histogram. Also I tried to make the outline bigger in white, but this will not show the correct length of the bar. Does anyone has an idea how to do that?
As two people wrote already in the comments, I also feel that your attempt to change the space between the 'bar' of a histogram is based on a misunderstanding about the nature of a histogram. Here the frequency of your events is represented as areas of the cells in the histogram. Or to quote Wikipedia:
the range of values—that is, divide the entire range of values into a series of intervals—and then count how many values fall into each interval
A priori these cells do not even need to have the same width (in the case your class widths would differ).
Perhaps what you are looking for is geom_bar (https://ggplot2.tidyverse.org/reference/geom_bar.html)
ggplot(data_csv, aes(x=Phasenew, fill=Success)) +
geom_bar()

Can I place my ggplot2 legend right beside the horizontal axis label?

In order to save as much as white space as I can, I would like to place the legend entry at the same height as the horizontal axis label. Can this be done and if so, how?
Here's a plot illustrating what I am hoping to achieve, with current and hoped-for legend position illustrated using a (manually added) green box.
I currently place the legend using theme(legend.position=c(0.87,0.1)) (noting that the exact coordinates are not relevant). Ideally, this route would allow for values outside of the [0,1] domain but it appears not to allow for that.
theme(legend.position="bottom") places the legend well outside of the plotting area, thus taking up more white space than I am willing to spare.
You just might have to play around with negative values regarding the y-coordinates of your legend.position-vector.
Here's an example:
library(ggplot2)
ggplot(iris, aes(Sepal.Width, Sepal.Length, color=Species))+
geom_line()+
facet_wrap(~Species)+
theme(legend.position=c(0.87,-0.01))
Note the -0.01 value. Is this what you're looking for?

going to full screen messes up ggplot figure

There is either a bug in ggplot or a bug in my brain.
The double green bar at height 27 should be a single line. It is defined by two x values and a single y value twice:
Even worse, if I expand the image to full screen more of these fly apart
Does anyone have any insight into this? Thanks.
ggplot() +
geom_line(data=plotData,
aes(x=x,y=y,group=interaction(y,type),color=color,
size=lineSize,linetype=lineType)) +
scale_color_manual(values=group.colors) +
ggtitle('EScells') +
xlab('chr2') +
ylab('')
Not surprisingly, the bug was in my brain. ggplot was treating the lines in question as dashed lines. Some of these dashed lines only became visible as dashes in the larger sized image.

R units of margins, text and points in a figure

I am trying to plot some data in a plot where I leave a big margin free to add other information, namely text and points.
I am now struggling with keeping the size of the margin, text and points in a fixed ratio. I want this so that the layout of the figure does not change every time I plot new data.
I have:
a<-8
counter<-1
spacing<-a/(3*a)
adding<-a/(3*a)
start<-a*(a/3)
alphabet<-c("A","A","A","A","A","A","A","A")
x<-c(1,2,3,4,5,6,7,8)
y<-c(10,20,30,40,50,60,70,80)
png(file="TESTING.png", units="in", width=a, height=a, res=a*100)
par(xpd=NA,mar=c(0,0,0,0),oma=c(0,0,0,(3*a))) #bottom, left,top, right
plot.new()
plot(x,y)
points(pch=20,10, 10, cex=5)
text(10,10, alphabet, cex=5, col="blue")
this creates the image below.
What I do not understand is why the size of the point and the text is not the same and why the margin can be "bigger" than the width of the figure.
BASICALLY, the units of the margins, the points and the text are not the same...
What I need is a way to make the size of the point and text AND the margin independent of the data I plot so that the figure always looks the same although there is more data in it in some cases (for example 10 or 20 points with text in the margin).
This could be done by setting the units of points, text and margin to inches so that a is the same for all of them...
Or to know the ratio between the different units used by R for margin, points and text...
Any ideas on how to solve that?
Please let me know if clarifications are needed!

geom_bar not showing every values

I want to draw a bar plot, with ggplot and geom_bar, but it seems that the behavior of geom_bar is not consistent. I don't understand why.
My data is a time series of precipitations:
library(ggplot2)
library(data.table)
library(lubridate)
set.seed(42)
dt1 <- data.table(dateHeure=seq(ymd_hms("2014-06-04 13:30:00"),
ymd_hms("2014-10-20 08:30:00"), by='1 hour'),
rain=sample(c(rep(5,15), rep(10,15), rep(20,10),
rep(30, 5), 40, rep(0, 3262))))
Then i plot it, and not all the data appears... Why is some data missing?
ggplot(data=dt1)+
geom_bar(aes(x=dateHeure, y=rain),
stat="identity",
fill="blue") # doesn't work!
But if i add the variable color in aes, then the plot is correct!
ggplot(data=dt1)+
geom_bar(aes(x=dateHeure, y=rain, color="rain"),
stat="identity",
width=0.2) # work properly
So someone know why geom_bar doesn't work properly without color? Because i can't rely on it if sometimes not all the data is correctly plotted...
thanks!
edit: to respond to #eipi10, i added the plots. The strange thing is that when i resize the plot window in the first case, the data which is plotted changes!
Based on the edit to your question, I think I know what's happening: In the first plot, you use fill="blue". But the bin widths are very small compared to the overall range of the x-axis. This results in very, very thin vertical bars--so thin that you can't see some of them on your screen, but they appear when you expand the physical width of the plot.
On the other hand, in your second plot you used colour="rain", which adds a border to each bar, making each bar thicker, so they are visible, even when the physical width of the plot is relatively small.
Try adding colour="blue"(or "red" or whatever) to your first plot and I think you'll see all the bars, even without resizing. On the other hand, try changing colour="rain" to fill="rain" on your second plot and see if that creates the "disappearing data" effect on your second plot.
UPDATE: In response to your comment, you can use the colour parameter and then set the line width to get exactly the bar thickness you want, so you don't really need fill. For example:
ggplot(data=dt1)+
geom_bar(aes(x=dateHeure, y=rain),
stat="identity",
colour="blue", lwd=0.5)
Just set lwd (line width) to a value that gives you the bar-width you want. And, of course, you can also change the colour as well.

Resources