You have two questions in one with two pretty straightforward answers:
1. How to force a discrete axis when your column is a continuous one? To make ggplot2
draw a discrete axis, the data must be discrete. You can force your numeric data to be discrete by converting to a factor. So, instead of x=Sites
in your plot code, use x=as.factor(Sites)
.
2. How to eliminate the white space below the columns in a column plot? You can control the limits of the y
axis via the scale_y_continuous()
function. By default, the limits extend a bit past the actual data (in this case, from 0 to the max Concentration). You can override that behavior via the expand=
argument. Check the documentation for expansion()
for more details, but here I'm going to use mult=
, which uses a multiplication to find the new limits based on the data. I'm using 0
for the lower limit to make the lower axis limit equal the minimum in your data (0
), and 0.05
as the upper limit to expand the chart limits about 5% past the max value (this is default, I believe).
Here's the code and resulting plot.
library(ggplot2)
df <- data.frame(
Sites = c(2,4,6,7,8,9,10,11,12,13,14,15,16,17),
Concentration = c(10,16,3,15,17,10,11,19,14,12,14,13,18,16)
)
ggplot(df, aes(x=as.factor(Sites), y=Concentration)) +
geom_col(color="black", fill="lightblue") +
scale_y_continuous(expand=expansion(mult=c(0, 0.05))) +
theme_bw()
