Bar plot with fix color for same category in pythonmaking matplotlib scatter plots from dataframes in Python's pandasWhy isn't my Pandas 'apply' function referencing multiple columns working?Plot a scatter plot in python with matplotlib with dictionaryPlotting sorted heatmap keeping (x,y) value colorsPython: Legend has wrong colors on Pandas MultiIndex plotMost pythonic way to plot multiple signalsPlot dataframe then add vertical lines; how get custom legend text for all?Assign same color to group of line plotscreating python plot with different color linesBar plot in Pandas from several dataframes
How to explain what's wrong with this application of the chain rule?
Store Credit Card Information in Password Manager?
Is there a name for this algorithm to calculate the concentration of a mixture of two solutions containing the same solute?
C++ debug/print custom type with GDB : the case of nlohmann json library
What if a revenant (monster) gains fire resistance?
Why electric field inside a cavity of a non-conducting sphere not zero?
Should I outline or discovery write my stories?
Is it improper etiquette to ask your opponent what his/her rating is before the game?
Added a new user on Ubuntu, set password not working?
Biological Blimps: Propulsion
copy and scale one figure (wheel)
How do I color the graph in datavisualization?
How can Trident be so inexpensive? Will it orbit Triton or just do a (slow) flyby?
Why can Carol Danvers change her suit colours in the first place?
Does a 'pending' US visa application constitute a denial?
Why is so much work done on numerical verification of the Riemann Hypothesis?
Drawing ramified coverings with tikz
How to implement a feedback to keep the DC gain at zero for this conceptual passive filter?
250 Floor Tower
Has any country ever had 2 former presidents in jail simultaneously?
How to bake one texture for one mesh with multiple textures blender 2.8
Fear of getting stuck on one programming language / technology that is not used in my country
What is this cable/device?
2.8 Why are collections grayed out? How can I open them?
Bar plot with fix color for same category in python
making matplotlib scatter plots from dataframes in Python's pandasWhy isn't my Pandas 'apply' function referencing multiple columns working?Plot a scatter plot in python with matplotlib with dictionaryPlotting sorted heatmap keeping (x,y) value colorsPython: Legend has wrong colors on Pandas MultiIndex plotMost pythonic way to plot multiple signalsPlot dataframe then add vertical lines; how get custom legend text for all?Assign same color to group of line plotscreating python plot with different color linesBar plot in Pandas from several dataframes
I have a simple dataframe
as follows:
Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 B XMA 0.482742
8 D VCD 0.469553
Now I would like to have a barplot with each value, and same color for each state if Condition is the same. I tried the following python code:
Data_Control = pd.ExcelFile('Bar_plot_example.xlsx')
df_Control= Data_Control.parse('Sheet2')# my dataframe
s = pd.Series(df_Control.iloc[:,2].values, index=df_Control.iloc[:,1])
colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
s.plot(kind='barh', color=[colors[i] for i in df_Control['Condition']])
plt.legend()
But I am not able to get legend correctly for each condition. I am getting the following plot.
So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.
python matplotlib
add a comment |
I have a simple dataframe
as follows:
Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 B XMA 0.482742
8 D VCD 0.469553
Now I would like to have a barplot with each value, and same color for each state if Condition is the same. I tried the following python code:
Data_Control = pd.ExcelFile('Bar_plot_example.xlsx')
df_Control= Data_Control.parse('Sheet2')# my dataframe
s = pd.Series(df_Control.iloc[:,2].values, index=df_Control.iloc[:,1])
colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
s.plot(kind='barh', color=[colors[i] for i in df_Control['Condition']])
plt.legend()
But I am not able to get legend correctly for each condition. I am getting the following plot.
So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.
python matplotlib
add a comment |
I have a simple dataframe
as follows:
Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 B XMA 0.482742
8 D VCD 0.469553
Now I would like to have a barplot with each value, and same color for each state if Condition is the same. I tried the following python code:
Data_Control = pd.ExcelFile('Bar_plot_example.xlsx')
df_Control= Data_Control.parse('Sheet2')# my dataframe
s = pd.Series(df_Control.iloc[:,2].values, index=df_Control.iloc[:,1])
colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
s.plot(kind='barh', color=[colors[i] for i in df_Control['Condition']])
plt.legend()
But I am not able to get legend correctly for each condition. I am getting the following plot.
So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.
python matplotlib
I have a simple dataframe
as follows:
Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 B XMA 0.482742
8 D VCD 0.469553
Now I would like to have a barplot with each value, and same color for each state if Condition is the same. I tried the following python code:
Data_Control = pd.ExcelFile('Bar_plot_example.xlsx')
df_Control= Data_Control.parse('Sheet2')# my dataframe
s = pd.Series(df_Control.iloc[:,2].values, index=df_Control.iloc[:,1])
colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
s.plot(kind='barh', color=[colors[i] for i in df_Control['Condition']])
plt.legend()
But I am not able to get legend correctly for each condition. I am getting the following plot.
So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.
python matplotlib
python matplotlib
edited Mar 8 at 5:07
Shanteshwar Inde
6231818
6231818
asked Mar 8 at 4:37
Vrutang ShahVrutang Shah
185
185
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
You can create the handles and labels for the legend directly from the data:
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
Complete example:
u = """ Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 B XMA 0.482742
8 D VCD 0.469553"""
import io
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(io.StringIO(u),sep="s+" )
s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])
colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
plt.show()
This also works! Thank you!
– Vrutang Shah
Mar 8 at 19:03
add a comment |
So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to plt.legend
.
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
# Get the original handles.
original_handles = plt.gca().get_legend_handles_labels()[0][0]
# Hold the handles and labels that will be passed to legend in lists.
handles = []
labels = []
conditions = df['Condition'].values
# Seen conditions helps us make sure that each label is added only once.
seen_conditions = set()
# Iterate over the condition and handle together.
for condition, handle in zip(conditions, original_handles):
# If the condition was already added to the labels, then ignore it.
if condition in seen_conditions:
continue
# Add the handle and label.
handles.append(handle)
labels.append(condition)
seen_conditions.add(condition)
# Call legend with the stored handles and labels.
plt.legend(handles, labels)
That works! Than you so much! Really nice code!
– Vrutang Shah
Mar 8 at 6:04
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056805%2fbar-plot-with-fix-color-for-same-category-in-python%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can create the handles and labels for the legend directly from the data:
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
Complete example:
u = """ Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 B XMA 0.482742
8 D VCD 0.469553"""
import io
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(io.StringIO(u),sep="s+" )
s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])
colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
plt.show()
This also works! Thank you!
– Vrutang Shah
Mar 8 at 19:03
add a comment |
You can create the handles and labels for the legend directly from the data:
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
Complete example:
u = """ Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 B XMA 0.482742
8 D VCD 0.469553"""
import io
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(io.StringIO(u),sep="s+" )
s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])
colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
plt.show()
This also works! Thank you!
– Vrutang Shah
Mar 8 at 19:03
add a comment |
You can create the handles and labels for the legend directly from the data:
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
Complete example:
u = """ Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 B XMA 0.482742
8 D VCD 0.469553"""
import io
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(io.StringIO(u),sep="s+" )
s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])
colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
plt.show()
You can create the handles and labels for the legend directly from the data:
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
Complete example:
u = """ Condition State Value
0 A AM 0.775651
1 B XP 0.700265
2 A HML 0.688315
3 A RMSML 0.666956
4 B XAD 0.636014
5 C VAP 0.542897
6 C RMSML 0.486664
7 B XMA 0.482742
8 D VCD 0.469553"""
import io
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(io.StringIO(u),sep="s+" )
s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])
colors = 'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")
plt.show()
answered Mar 8 at 10:21
ImportanceOfBeingErnestImportanceOfBeingErnest
139k13161239
139k13161239
This also works! Thank you!
– Vrutang Shah
Mar 8 at 19:03
add a comment |
This also works! Thank you!
– Vrutang Shah
Mar 8 at 19:03
This also works! Thank you!
– Vrutang Shah
Mar 8 at 19:03
This also works! Thank you!
– Vrutang Shah
Mar 8 at 19:03
add a comment |
So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to plt.legend
.
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
# Get the original handles.
original_handles = plt.gca().get_legend_handles_labels()[0][0]
# Hold the handles and labels that will be passed to legend in lists.
handles = []
labels = []
conditions = df['Condition'].values
# Seen conditions helps us make sure that each label is added only once.
seen_conditions = set()
# Iterate over the condition and handle together.
for condition, handle in zip(conditions, original_handles):
# If the condition was already added to the labels, then ignore it.
if condition in seen_conditions:
continue
# Add the handle and label.
handles.append(handle)
labels.append(condition)
seen_conditions.add(condition)
# Call legend with the stored handles and labels.
plt.legend(handles, labels)
That works! Than you so much! Really nice code!
– Vrutang Shah
Mar 8 at 6:04
add a comment |
So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to plt.legend
.
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
# Get the original handles.
original_handles = plt.gca().get_legend_handles_labels()[0][0]
# Hold the handles and labels that will be passed to legend in lists.
handles = []
labels = []
conditions = df['Condition'].values
# Seen conditions helps us make sure that each label is added only once.
seen_conditions = set()
# Iterate over the condition and handle together.
for condition, handle in zip(conditions, original_handles):
# If the condition was already added to the labels, then ignore it.
if condition in seen_conditions:
continue
# Add the handle and label.
handles.append(handle)
labels.append(condition)
seen_conditions.add(condition)
# Call legend with the stored handles and labels.
plt.legend(handles, labels)
That works! Than you so much! Really nice code!
– Vrutang Shah
Mar 8 at 6:04
add a comment |
So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to plt.legend
.
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
# Get the original handles.
original_handles = plt.gca().get_legend_handles_labels()[0][0]
# Hold the handles and labels that will be passed to legend in lists.
handles = []
labels = []
conditions = df['Condition'].values
# Seen conditions helps us make sure that each label is added only once.
seen_conditions = set()
# Iterate over the condition and handle together.
for condition, handle in zip(conditions, original_handles):
# If the condition was already added to the labels, then ignore it.
if condition in seen_conditions:
continue
# Add the handle and label.
handles.append(handle)
labels.append(condition)
seen_conditions.add(condition)
# Call legend with the stored handles and labels.
plt.legend(handles, labels)
So I haven't worked much with plotting directly from pandas, but you'll have to access the handles and use that to construct lists of handles and labels that you can pass to plt.legend
.
s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
# Get the original handles.
original_handles = plt.gca().get_legend_handles_labels()[0][0]
# Hold the handles and labels that will be passed to legend in lists.
handles = []
labels = []
conditions = df['Condition'].values
# Seen conditions helps us make sure that each label is added only once.
seen_conditions = set()
# Iterate over the condition and handle together.
for condition, handle in zip(conditions, original_handles):
# If the condition was already added to the labels, then ignore it.
if condition in seen_conditions:
continue
# Add the handle and label.
handles.append(handle)
labels.append(condition)
seen_conditions.add(condition)
# Call legend with the stored handles and labels.
plt.legend(handles, labels)
answered Mar 8 at 5:45
Shashank AgarwalShashank Agarwal
1,8781520
1,8781520
That works! Than you so much! Really nice code!
– Vrutang Shah
Mar 8 at 6:04
add a comment |
That works! Than you so much! Really nice code!
– Vrutang Shah
Mar 8 at 6:04
That works! Than you so much! Really nice code!
– Vrutang Shah
Mar 8 at 6:04
That works! Than you so much! Really nice code!
– Vrutang Shah
Mar 8 at 6:04
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056805%2fbar-plot-with-fix-color-for-same-category-in-python%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown