How do I manually change the key labels in a legend in ggplot2

前端 未结 2 755
陌清茗
陌清茗 2020-11-30 03:38

I am preparing a plot for publication. I created a stacked box plot to show frequency of patients in each group who were some complicated accumulation of seronegatives versu

相关标签:
2条回答
  • 2020-11-30 04:11

    The standard way is to use the scale functions to change the displayed labels for groups. You can replace your ggplot call with

    ggplot(data, aes(grp, fill=outcome)) + geom_bar() +xlab("group") +
      ylab("number of subjects") + 
      scale_fill_discrete("Serologic response", 
                          breaks=c("(10.1,79.9]","(79.9,150]"), 
                          labels=c("double negative", "positive for a and/or b"))
    

    Note that the scale's title has been incorporated into the scale_fill_discrete call. You can do this with the axes too, if you like

    ggplot(data, aes(grp, fill=outcome)) + geom_bar() +
      scale_x_discrete("group") +
      scale_y_continuous("number of subjects") + 
      scale_fill_discrete("Serologic response", 
                          breaks=c("(10.1,79.9]","(79.9,150]"), 
                          labels=c("double negative", "positive for a and/or b"))
    
    0 讨论(0)
  • 2020-11-30 04:21

    I found a hybrid way of doing it. It does relabel the factor but I do not have to do it in the dataframe. Instead I just do it in the ggplot command.

    ggplot(data, aes(grp, fill=factor(outcome,labels=c("low","high")))) + 
      geom_bar() +xlab("group") +ylab("number of subjects") +
       labs(fill="Serologic response")
    

    Are there any other ways?

    0 讨论(0)
提交回复
热议问题