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 is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?
Writing rule stating superpower from different root cause is bad writing
Smoothness of finite-dimensional functional calculus
can i play a electric guitar through a bass amp?
Fully-Firstable Anagram Sets
"to be prejudice towards/against someone" vs "to be prejudiced against/towards someone"
How to format long polynomial?
Is this a crack on the carbon frame?
Modeling an IPv4 Address
Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)
A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?
Test whether all array elements are factors of a number
Can a Warlock become Neutral Good?
What would happen to a modern skyscraper if it rains micro blackholes?
Have astronauts in space suits ever taken selfies? If so, how?
Minkowski space
Why do falling prices hurt debtors?
Service Entrance Breakers Rain Shield
What do you call a Matrix-like slowdown and camera movement effect?
How old can references or sources in a thesis be?
Fencing style for blades that can attack from a distance
What's the point of deactivating Num Lock on login screens?
How can I make my BBEG immortal short of making them a Lich or Vampire?
Theorems that impeded progress
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
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
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
79811018
79811018
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
141k13166243
141k13166243
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