How to Reverse Legend (Labels and Color) So High Value Starts at Bottom

Flip ordering of legend without altering ordering in plot

You're looking for guides:

ggplot(dTbl, aes(x=factor(y),y=x, fill=z)) +
geom_bar(position=position_dodge(), stat='identity') +
coord_flip() +
theme(legend.position='top', legend.direction='vertical') +
guides(fill = guide_legend(reverse = TRUE))

I was reminded in chat by Brian that there is a more general way to do this for arbitrary orderings, by setting the breaks argument:

ggplot(dTbl, aes(x=factor(y),y=x, fill=z)) +
geom_bar(position=position_dodge(), stat='identity') +
coord_flip() +
theme(legend.position='top', legend.direction='vertical') +
scale_fill_discrete(breaks = c("r","q"))

Reverse stacking order without affecting legend order in ggplot2 bar charts

You can reverse the legend order using scale_fill_discrete:

ggplot(mtcars, aes(factor(cyl), fill=gear)) + geom_bar() + 
scale_fill_discrete(guide=guide_legend(reverse=T))

Plot of reversed legend order

reverse order in R leaflet continuous legend

Unfortunately the accepted answer to this will get the numbers out of alignment (in fact exactly reversed) from the colours they represent.

Here's the original proposed solution, which I say is incorrect:

map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')
x <- 1:100
pal <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x)
map %>% addLegend('topright', pal=pal, values=x)

# This solution shows 100 as red
map %>% addLegend('topright',
pal = pal,
values = x,
labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))

Sample Image

But if you've been using the pal() function to draw anything on your map, you now have it exactly wrong.

# But 100 is blue, not red
plot(1, 1, pch = 19, cex = 3, col = pal(100))

Sample Image

I think the solution is to define to functions that allocate colours to numbers, one in reverse for the legend, and one for actually drawing things:

pal_rev <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x, reverse = TRUE)

map %>% addLegend('topright',
pal = pal_rev,
values = x,
labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))

This gives us a legend that matches anything we will have drawn ie 100 is now correctly shown to be blue:

Sample Image

Reverse the order of a legend

You could call

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2016)

C0 = list('ABCDEF')
C2 = np.random.randint(20000, size=(len(C0), 3))
width = 1.0
C1 = ['foo', 'bar', 'baz']
ind = np.linspace(-width, width, len(C1))

colorsArr = plt.cm.BuPu(np.linspace(0, 0.5, len(C2)))
fig = plt.figure(figsize=(11,11))
ax = fig.add_subplot(1, 1, 1)

prevBar = 0
for height, color, label in zip(C2, colorsArr, C0):
h = ax.bar(ind, height, width, bottom=prevBar, color=color, label=label)
prevBar = prevBar + height

plt.ylabel('Home Category')
plt.title('Affinity - Retail Details(Home category)')

# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(width/2.0) for i in ind]
# set the x ticks with names
plt.xticks(tick_pos, C1)
plt.yticks(np.arange(0,70000,3000))

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')

plt.show()

Sample Image

Invert the ordering of labels in the ggplot color scale after discretizing a continuous variable

You can use the guide_legend argument reverse to reverse the legend.

scale_fill_brewer(palette = "RdYlGn", direction = -1, name = "Response",
guide = guide_legend(reverse = TRUE))

Switch Legend Order

If you want the invert the order of legend lines and keeping labels as they are, you have to invert the order of legend handles.

You should get handles and labels from the axis where you are plotting:

handles, labels = ax.get_legend_handles_labels()

then pass them to the legend, inverting the order of handles:

ax.legend(handles = handles[::-1], labels = labels)

Example of working code

import matplotlib.pyplot as plt


fig, ax = plt.subplots(1, 2)

ax[0].plot([0, 1], [1, 1], color = 'red', label = 'line 1')
ax[0].plot([0, 1], [2, 2], color = 'blue', label = 'line 2')
ax[0].plot([0, 1], [3, 3], color = 'gold', label = 'line 3')

ax[0].legend(frameon = True, loc = 'upper left', bbox_to_anchor = (1.05, 1))

ax[1].plot([0, 1], [1, 1], color = 'red', label = 'line 1')
ax[1].plot([0, 1], [2, 2], color = 'blue', label = 'line 2')
ax[1].plot([0, 1], [3, 3], color = 'gold', label = 'line 3')

handles, labels = ax[1].get_legend_handles_labels()
ax[1].legend(handles = handles[::-1], labels = labels, frameon = True, loc = 'upper left', bbox_to_anchor = (1.05, 1))

plt.tight_layout()

plt.show()

Sample Image

How to reverse the legend order in a plot created with sjPlot

As you are basically dealing with a ggplot you could reverse the order of the legend via guide_legend:

library(lme4)
#> Loading required package: Matrix
library(ggplot2)

mdl <- lmer(disp~mpg:wt+vs+(1|cyl) , data = mtcars)

sjPlot::plot_model(mdl,type = 'pred',terms = c("mpg [all]","wt")) +
guides(color = guide_legend(reverse = TRUE))

Sample Image



Related Topics



Leave a reply



Submit