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()
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))
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()
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 tracelegendgroup
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')
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')
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
Related Topics
Changing Values When Converting Column Type to Numeric
Print Pretty Data.Frames/Tables to Console
Relocating Alaska and Hawaii on Thematic Map of the Usa with Ggplot2
How to Cross-Paste All Combinations of Two Vectors (Each-To-Each)
Change Path.Expand Location (Win 7)
Add Text on Top of a Faceted Dodged Bar Chart
How to Cumulatively Add Values in One Vector in R
"Set Difference" Between Two Vectors with Duplicate Values
Read Observations in Fixed Width Files Spanning Multiple Lines in R
Correctly Specifying "Logical Conditions" (In R)
Removing Specific Rows from a Dataframe
How to Group by Two Columns in R
Optimized Rolling Functions on Irregular Time Series with Time-Based Window
Edit Datatable in Shiny with Dropdown Selection for Factor Variables
R Shiny Table Not Rendering HTML
Combining New Lines and Italics in Facet Labels with Ggplot2
How to Use R Plotly Library in R Script Visual of Power Bi
Maps, Ggplot2, Fill by State Is Missing Certain Areas on the Map