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?
CodePudding user response:
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:
CodePudding user response:
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.