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

3
  • Welcome to SO! It would be easier to help you if you provide a minimal 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. Commented Mar 19, 2022 at 8: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)). Commented Mar 19, 2022 at 8:45
  • @stefan thank you. do you have any solution for the first problem? Commented Mar 19, 2022 at 15:53

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.