0

I want to plot a bar chart and use scale_x_discrete to manually describe the bars. The x variable has 9 levels, the group-variable has 3 levels.

ggplot(data, aes(x = education, group = food, fill = food)) +
geom_bar() +
scale_x_discrete(limits=c("A","B","C","D","E","F","G","H","I"))

I did the same plot with the two other x-variables and it worked perfectly. This one works without the scale_x_discrete function, but as soon as I use it to give shorter names to the bars, I get the following error:

Warning message: Removed 979 rows containing non-finite values (stat_count).

There are no NAs, but for some levels of x there is only one level of the group-variable "food", which isn't the case for the other variables I plotted, so that might be part of the problem. What could be a solution?

Peter
  • 11,500
  • 5
  • 21
  • 31
Paul Sc
  • 5
  • 1
  • Welcome to SO, Paul Sc! Questions on SO (especially in R) do much better if they are reproducible and self-contained. By that I mean including attempted code (please be explicit about non-base packages), sample representative data (perhaps via `dput(head(x))` or building data programmatically (e.g., `data.frame(...)`), possibly stochastically), perhaps actual output (with verbatim errors/warnings) versus intended output. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Mar 04 '22 at 14:18
  • 1
    try `scale_x_discrete(labels=c("A","B","C","D","E","F","G","H","I"))` – AndS. Mar 04 '22 at 15:37
  • Thank you AndS. Using "labels" instead of "limits" did work! – Paul Sc Mar 07 '22 at 08:36

2 Answers2

0

Sample data:

education=c("A","B","C","D","E","F","G","H","I")
food=c("Soup","Vegan","Meat","Raw","Soup","Vegan","Meat","Raw", "Vegan" )

data=cbind(education,food)
data<-data.frame(data) # make sure that your data is a df

Sample code:

ggplot(data, aes(x = education, group = food, fill = food)) +
  geom_bar() +
  #scale_x_discrete(limits=c("A","B","C","D","E","F","G","H","I"))+
   scale_x_discrete(labels=c("A","B","C","D","E","F","G","H","I"))+
  labs(y="Count", x="Education", fill="Food type")+
  theme_bw()

Output:

enter image description here

Rfanatic
  • 2,224
  • 1
  • 5
  • 21
  • Hi. Thanks for the idea, though it didn't solve the problem. However, using "labels" instead of "limits", as supposed in one of the comments above did work. – Paul Sc Mar 07 '22 at 08:42
  • @PaulSc thanks, in this case you can use labels=c() or limits=c() as well. updated the code – Rfanatic Mar 07 '22 at 08:48
-1

Using scale_x_discrete(labels=c("A","B","C","D","E","F","G","H","I")) (instead of limits ) did work. Thanks to AndS. who posted this solution in a comment above.

Paul Sc
  • 5
  • 1