简体   繁体   中英

Factor levels and scale_fill_manual() arguments ignored in ggplot R

I am plotting a graph but the order of the factor levels that I assign as well as the function scale_fill_manual() are ignored by ggplot.

The dataset is the german credit dataset that can be found in the UCI Machine Learning repository and the code is the following:

 german_fct_train$Status_of_existing_account <- factor(german_fct_train$Status_of_existing_account , 
                            levels = c("No_Account" , "less_than_0" , "between_0_and_200" ,  "greater_equal_to_200"))
german_fct_train$Class <- factor(german_fct_train$Class, levels = c("1" , "0"))

ggplot( german_fct_train, aes( F_Credit_history, F_Status_of_existing_account)) +
  geom_jitter(aes(color = Class), size = 3, alpha = 0.5) +  theme_economist() + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) + ggtitle("Status of existing checking account 
  and Credit History by Class") +
  xlab("Credit History") + ylab("Status of existing account") + 
  labs(fill="Class") +
  scale_fill_manual(limits= c("1", "0"), labels = c("Bad Customers" , "Good Customers"),  values = c("red", 'blue'))

在此处输入图片说明

Your advice will be appreciated.

In your example, I would recommend factoring the Class outside of ggplot, and then applying the scale_fill_manual without adding labels which is most likely causing the issue. Here is an example with mtcars

data("mtcars")
library(ggplot)
ggplot(mtcars, aes(factor(carb), factor(gear))) +
  geom_jitter(aes(color = factor(gear)), size = 3, alpha = 0.5) + 
  scale_fill_manual(values = c("red", 'blue', 'darkgoldenrod'))+
  xlab("Credit History") + ylab("Status of existing account") + 
  labs(x="Credit History", y="Status of existing account",
       title = "Status of existing checking account and Credit History by Class") +
  theme_light() + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

Also i would also recommend using the labs call instead of xlab , ylab , and ggtitle . Lastly, ggplot has a tendency to like theme at the end of the call, which may also be causing some errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM