0

Aim: plot a column chart representing concentration values at discrete sites

Problem: the 14 site labels are numeric, so I think ggplot2 is assuming continuous data and adding spaces for what it sees as 'missing numbers'. I only want 14 columns with 14 marks/labels, relative to the 14 values in the dataframe. I've tried assigning the sites as factors and characters but neither work.

Also, how do you ensure the y-axis ends at '0', so the bottom of the columns meet the x-axis?

Thanks

Data:

Sites: 2,4,6,7,8,9,10,11,12,13,14,15,16,17
Concentration: 10,16,3,15,17,10,11,19,14,12,14,13,18,16

plot

benson23
  • 16,369
  • 9
  • 19
  • 38
Paul
  • 5
  • 3

1 Answers1

1

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()

enter image description here

chemdork123
  • 12,369
  • 2
  • 16
  • 32