强制图例中的级别顺序与双向条形图中的级别相同 [英] Forcing order of levels in the legend to be the same as in the bidirectional bar chart

查看:48
本文介绍了强制图例中的级别顺序与双向条形图中的级别相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是对此

我的问题是,通过按照我上面链接的问题使图表双向,图表和图例中类别的顺序不再对齐.在这种情况下,我想将图例中的顺序更改为与图表中相同的顺序.请注意,由于绘图的双向特性,这不是简单的重新调整因子水平的问题.

是否可以在图例中引用与图表中不同的变量?如果是这样,我可以复制关键变量并重新设置图例的级别.但是,否则我在努力提出解决方案.

解决方案

条形图的顺序取决于数据的顺序,即数据在图形中的显示方式.希望这也适用于您的数据!

  data_example<-data_frame(key = c("good","middle","poor"),结果= c(0.79,0.12,0.09))data_example<-mutate(data_example,key = fct_relevel(key,"good","poor","middle"),yscore = if_else(key =="good",结果,结果* -1))绘图<-ggplot(data_example,aes(x = 1,y = yscore,fill = key))+geom_col()+ scale_fill_discrete(breaks = as.character(data_example $ key))阴谋 

如果这不是理想的,因为您想自定义数据本身的顺序,我将重新排列数据或因子水平,然后将其通过管道传输到 ggplot()

来源: http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/

My question is a follow-up to this question and answer.

I have the following data and chart:

library(tidyverse)
data_example <- data_frame(key = c("good", "middle", "poor"), result = c(0.79, 0.12, 0.09))
data_example <- mutate(data_example, key = fct_relevel(key, "good", "poor", "middle"), 
                       yscore = if_else(key == "good", result, result * -1))

ggplot(data_example, aes(x = 1, y = yscore, fill = key)) +
  geom_col()

My problem is that by making the chart bidirectional as per the question I linked to above, the order of the categories in the chart and in the legend no longer line up. In this case, I'd like to change the order in the legend to the same order as in the chart. Note that this is NOT a simple issue of releveling factor levels because of the bidirectional nature of the plot.

Is it possible to reference a different variable in the legend than in the chart? If so, I could just duplicate the key variable and relevel the levels back for the legend. But I'm otherwise struggling to come up with a solution.

解决方案

Order of the bars depends on order of your data, which is how its displayed in the graph. Hopefully this works with your data too!

    data_example <- data_frame(key = c("good", "middle", "poor"), result = c(0.79, 0.12, 0.09))
    data_example <- mutate(data_example, key = fct_relevel(key, "good", "poor", "middle"), 
                   yscore = if_else(key == "good", result, result * -1))
    plot <- ggplot(data_example, aes(x = 1, y = yscore, fill = key)) +
      geom_col() + scale_fill_discrete(breaks = as.character(data_example$key))
    plot

If this isn't ideal since you want to customize the order of the data itself, I'd rearrange the data or factor levels, and pipe that into ggplot()

source: http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/

这篇关于强制图例中的级别顺序与双向条形图中的级别相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆