0

So I have this graph:

Graph with default labels

But I would like to add appropriate labels to the x axis so each column has a label. For this I used scale_x_discrete(limit = as.character(2008:2017)) however doing so gives this result:

graph with scale_x_discrete(limit)

As you can see the labels are all squashed to one side and the data bars to the other.

Am I doing something wrong? or is this bug?

Here is my code:

# First image
ggplot(data_melt, aes(x = year, y = value, fill = variable)) +

  geom_bar(position = "fill", stat = "identity") +

  theme(legend.position = "none")

# Second image
ggplot(data_melt, aes(x = year, y = value, fill = variable)) +

  geom_bar(position = "fill", stat = "identity") +

  theme(legend.position = "none") +

  scale_x_discrete(limit = as.character(2008:2017)) 

Gorka
  • 1,971
  • 1
  • 13
  • 28
cach dies
  • 331
  • 1
  • 14
  • It will be much easier to help if you provide at least a sample of your data with `dput(data_melt)` or if your data is very large `dput(data_melt[1:50,])`. You can edit your question and paste the output. You can surround it with three backticks (```) for better formatting. See [How to make a reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for more info. – Ian Campbell May 08 '20 at 20:35
  • @IanCampbell, thanks for your help. Since Gorka´s solution works I believe that won't be necessary (I didn't include a data sample since long posts tend to be ignored). – cach dies May 09 '20 at 00:23

1 Answers1

0

Your labeling problem is due to the variable type and it has not nothing to do with the axis scale. Try changing the variable, in the x axis, from numerical to categorical:

data_melt$year <- as.factor(data_melt$year)
Gorka
  • 1,971
  • 1
  • 13
  • 28
  • Thanks this works perfectly: for anyone who is reading this you must declare `year` as a factor and do not include the option `scale_x_discrete()`. To me this makes sense since this forces `ggplot` to treat each year differently instead as part of a continuum. – cach dies May 09 '20 at 00:28