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













3















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



So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.










share|improve this question




























    3















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



    So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.










    share|improve this question


























      3












      3








      3








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



      So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.










      share|improve this question
















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



      So how should I get correct legend for each condition? Any help is highly appreciated, Thanks.







      python matplotlib






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 8 at 5:07









      Shanteshwar Inde

      6231818




      6231818










      asked Mar 8 at 4:37









      Vrutang ShahVrutang Shah

      185




      185






















          2 Answers
          2






          active

          oldest

          votes


















          1














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


          enter image description here






          share|improve this answer























          • This also works! Thank you!

            – Vrutang Shah
            Mar 8 at 19:03


















          2














          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)





          share|improve this answer























          • That works! Than you so much! Really nice code!

            – Vrutang Shah
            Mar 8 at 6:04










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



          );













          draft saved

          draft discarded


















          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









          1














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


          enter image description here






          share|improve this answer























          • This also works! Thank you!

            – Vrutang Shah
            Mar 8 at 19:03















          1














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


          enter image description here






          share|improve this answer























          • This also works! Thank you!

            – Vrutang Shah
            Mar 8 at 19:03













          1












          1








          1







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


          enter image description here






          share|improve this answer













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


          enter image description here







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 10:21









          ImportanceOfBeingErnestImportanceOfBeingErnest

          139k13161239




          139k13161239












          • 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





          This also works! Thank you!

          – Vrutang Shah
          Mar 8 at 19:03













          2














          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)





          share|improve this answer























          • That works! Than you so much! Really nice code!

            – Vrutang Shah
            Mar 8 at 6:04















          2














          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)





          share|improve this answer























          • That works! Than you so much! Really nice code!

            – Vrutang Shah
            Mar 8 at 6:04













          2












          2








          2







          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)





          share|improve this answer













          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)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          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

















          • 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

















          draft saved

          draft discarded
















































          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.




          draft saved


          draft discarded














          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





















































          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







          Popular posts from this blog

          Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

          2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

          Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme