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!
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)/