-1

I want to create a barchart of some data, I collected from a survey using the R programming language. The X values of my data range between 4-10 but I want my xaxis to range between 0-10 to display the full range of variables that my survey could have possibly given.

Data:

X = 4 5 6 7 8 9 10 

Y = 5 7 2 10 5 2 5

I have tried:

barplot(data, xlim(0,10),xpd=TRUE)

I've also tried using the 'expand_limits' function in ggplot2 with no avail either. This hasnt done what I expected. I want my graph to range between 0 and 10 with bars only plotted on x values of 4-10.

If someone could help me I'd be really thankful.

Graham
  • 1
  • 2
  • Your code does not work, please make questions copy-paste reproducible, help: [how-to-make-a-great-r-reproducible-example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) – jay.sf Jun 29 '20 at 13:58

2 Answers2

1

Welcome to SO!

The barplot function doesn't really have an "x-axis", as you can see. If you try using the limits, it will assume that the first height you give it is the height number 1 and so on, and put the "empty space" at the end.

Alternatively, this ggplot2 solution should work:

library(ggplot2)
ggplot(df, aes(X, Y)) +
    geom_col(color = "black", fill = "grey60") +
    lims(x = c(0,10.5)) +
    theme_classic()

ggbarplot

You can read more about it to tweak the plot style.

csgroen
  • 2,511
  • 11
  • 28
  • 1
    I think this is how I would actually do it rather than the somewhat more limited `barplot`. Remember you can use `geom_col` instead of `geom_bar(stat = "identity")` – Allan Cameron Jun 29 '20 at 14:05
  • Cheers @csgroen ! Yeah, there really isnt that much info in the help pages on precisely this problem and I've been tearing my hair out all morning trying to fix something that should be so simple. Thanks for your help! – Graham Jun 29 '20 at 14:15
  • Thanks @AllanCameron, I keep forgetting about `geom_col`. Edited to use that ;) – csgroen Jun 29 '20 at 14:22
0

A barplot is really for categorical variables, so if you convert your X variable to a factor and include all the levels you want, you should get the desired plot:

data <- data.frame(X = factor(c(4, 5, 6, 7, 8, 9, 10), levels = 1:10),
                   Y = c(5, 7, 2, 10, 5, 2, 5))

barplot(Y ~ X, data = data, xpd=TRUE)

Created on 2020-06-29 by the reprex package (v0.3.0)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87