Flip Ordering of Legend Without Altering Ordering in Plot

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 legend order without changing bar order in plotly express bar plot

Add legend={'traceorder': 'reversed'} to the update_layout statement:

import plotly.express as px
df = px.data.tips()
# Sort to put dinner on top.
df.sort_values('time', ascending=False, inplace=True)
fig = px.bar(df, y='sex', x='total_bill', color='time', barmode='group',
orientation='h')
fig.update_layout(yaxis={'categoryorder': 'total ascending'},
legend={'traceorder': 'reversed'})
fig.show()

result of plot

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 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

Rearrange stacked barplot legend labels without changing plot (and fix tick marks) in R

Found the answer here!: Flip ordering of legend without altering ordering in plot

Just add this code to the end of the ggplot: + guides(fill = guide_legend(reverse = TRUE))

Customizing the order of legends in plotly

You can use traceorder key for legend:

Determines the order at which the legend items are displayed. If
"normal", the items are displayed top-to-bottom in the same order as
the input data. If "reversed", the items are displayed in the opposite
order as "normal". If "grouped", the items are displayed in groups
(when a trace legendgroup is provided). if "grouped+reversed", the
items are displayed in the opposite order as "grouped".

In your case, you should modify your layout definition:

layout = go.Layout(
barmode='stack',
title=f'{measurement}',
xaxis=dict(
title='Count',
dtick=0),
yaxis=dict(
tickfont=dict(
size=10,
),
dtick=1),
legend={'traceorder':'normal'})
)

without traceorder specification

import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)

trace1 = go.Bar(x=['A', 'B', 'C'],
y=[20, 14, 23],
name='first')
trace2 = go.Bar(x=['A', 'B', 'C'],
y=[12, 18, 29],
name='second')

data = [trace1, trace2]
layout = go.Layout(barmode='stack',)

fig = go.Figure(data=data, layout=layout)
iplot(fig, filename='stacked-bar')

Sample Image

with traceorder specification

import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)

trace1 = go.Bar(x=['A', 'B', 'C'],
y=[20, 14, 23],
name='first')
trace2 = go.Bar(x=['A', 'B', 'C'],
y=[12, 18, 29],
name='second')

data = [trace1, trace2]
layout = go.Layout(barmode='stack',
legend={'traceorder':'normal'})

fig = go.Figure(data=data, layout=layout)
iplot(fig, filename='stacked-bar')

Sample Image

Custom order of legend in ggplot2 so it doesn't match the order of the factor in the plot

Unfortunately, I could not reproduce your figure fully as it seems that I'm missing your med data.

However, changing the levels in your data frame accordingly should do the trick. Just do the following before the ggplot() command:

levels(df$value) <- c("Very Important", "Important", "Less Important", 
"Not at all Important", "Strongly Satisfied",
"Satisfied", "Strongly Dissatisfied", "Dissatisified", "N/A")

Edit

Being able to reproduce your example, I came up with the following, a bit hacky, solution.

p <- ggplot(df, aes(x=Benefit, y = Percent, fill = value, label=abs(Percent))) +
geom_bar(stat="identity", width = .5, position = position_stack(reverse = TRUE)) +
geom_col(position = 'stack') +
scale_x_discrete(limits = rev(levels(df$Benefit))) +
geom_text(position = position_stack(vjust = 0.5),
angle = 45, color="black") +
coord_flip() +
scale_fill_manual(labels = c("Very Important", "Important", "Less Important",
"Not at all Important", "Strongly Satisfied",
"Satisfied", "N/A"),values = col4) +
scale_y_continuous(breaks=(seq(-100,100,25)), labels=abs(seq(-100,100,by=25)), limits=c(-100,100)) +
theme_minimal() +
theme(
axis.title.y = element_blank(),
legend.position = c(0.85, 0.8),
legend.title=element_text(size=14),
axis.text=element_text(size=12, face="bold"),
legend.text=element_text(size=12),
panel.background = element_rect(fill = "transparent",colour = NA),
plot.background = element_rect(fill = "transparent",colour = NA),
#panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank()
)+
labs(fill="") + ylab("") + ylab("Percent") +
annotate("text", x = 9.5, y = 50, label = "Importance") +
annotate("text", x = 8.00, y = 50, label = "Satisfaction") +
guides(fill = guide_legend(override.aes = list(fill = c("#81A88D","#ABDDDE","#F4B5BD","#B40F20","orange","#F3DF6C","gray")) ) )
p

Sample Image



Related Topics



Leave a reply



Submit