1

Firstly, on the 1st row of X-axis, I have got labels like "white.highinc" that is the income for race white, but I have already a category for income level, so I just want the labels to be like white, black etc. for each set of columns.

Second, when I use "scale_fill_manual" function to get different colours for each year, the R shows "Error: Continuous value supplied to discrete scale". But in my data frame YEAR is discrete not continuous. In my data frame there are only three years 1995, 2005 and 2010. What should I do?

ggplot(data = data1, aes(x = interaction(race_code, inc_level, lex.order = TRUE), y = percent_lwpr, group = YEAR, fill=YEAR)) +
  geom_bar(stat="identity", position=position_dodge(width=0.8)) +
  scale_fill_manual(values=c("#ffa600", "#ff6361", "#bc5090"))+
  facet_grid(~inc_level, switch = "x", scales = "free_x", space = "free_x")+
  theme(panel.spacing = unit(0, "lines"), 
        strip.background = element_blank(),
        strip.placement = "outside") 

mygraph

upoma
  • 11
  • 2
  • Welcome to SO! It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. If you want to post your data type `dput(NAME_OF_DATASET)` into the console and copy the output starting with `structure(....` into your post. If your dataset has a lot of observations you could do e.g. `dput(head(NAME_OF_DATASET, 10))` for the first ten rows of data. – stefan Mar 19 '22 at 08:42
  • ... this said. The issue with `scale_fill_manual` could be fixed by converting your YEAR column (which is a numeric) to a discrete variable, e.g. do `..., aes(..., fill = factor(YEAR))`. – stefan Mar 19 '22 at 08:45
  • @stefan thank you. do you have any solution for the first problem? – upoma Mar 19 '22 at 15:53

1 Answers1

1

To fix your issue with the labels you could pass a function to the labels argument of scale_x_discrete which using gsub removes the unwanted part of the label starting with the ..

Using a subset of the ggplot2::mpg dataset as example data:

library(ggplot2)

mpg2 <- mpg[mpg$manufacturer %in% c("audi", "volkswagen"), ]

ggplot(mpg2, aes(interaction(class, manufacturer, lex.order = TRUE), fill = factor(year))) +
  geom_bar(position = position_dodge()) +
  scale_x_discrete(labels = ~ gsub("\\..*$", "", .x)) +
  facet_grid(~manufacturer, switch = "x", scales = "free_x", space = "free_x")+
  theme(panel.spacing = unit(0, "lines"), 
        strip.background = element_blank(),
        strip.placement = "outside")

stefan
  • 90,330
  • 6
  • 25
  • 51